Thread 中 Susend()和Resume过时的解决办法

在C#中对线程进行暂停时 发现Suspend()和Resume()过时,找了最后发现这样可以比较简单的解决这个问题

 	private static bool State = true;
    static AutoResetEvent ResetThr = new AutoResetEvent(false);
    //后台线程执行的方法
    public static void Add()
    {
        while (true)
        {
            for (int i = 0; i < 1000; i++)
            {
                if (!State)
                {
                    ResetThr.WaitOne();
                }
                Console.WriteLine(i);
                Thread.Sleep(500);
                i++;
            }
        }
    }
	//暂停
    public static void Stop()
    {
        State = false;
    }
    //继续
    public static void Continue()
    {
        State = true;
        ResetThr.Set();
    }

这样做的另外好处是可以很明确的设置暂停位,以防在程序不想停止的地方将线程挂起.

猜你喜欢

转载自blog.csdn.net/Good_StudyDaydayUp/article/details/83304091
今日推荐