C# Threading.Suspend in Obsolete, thread has been deprecated?

前端 未结 3 1421
忘掉有多难
忘掉有多难 2021-02-05 22:19

In my application, I am performing my file reading by another thread(other that GUI thread). There are two buttons that suspend and resume the Thread respectively.



        
3条回答
  •  暖寄归人
    2021-02-05 23:02

    I would use the Monitor mechanism for achieving pausing and resuming threads. The Monitor.Wait will cause the thread to wait for the Monitor.Pulse.

    private bool _pause = false;
    private object _threadLock = new object();
    
    private void RunThread()
    {
        while (true)
        {
            if (_pause)
            {
                lock (_threadLock)
                {
                    Monitor.Wait(_threadLock);
                }
            }
    
            // Do work
        }
    }
    
    private void PauseThread()
    {
        _pause = true;
    }
    
    private void ResumeThread()
    {
        _pause = false;
        lock (_threadLock)
        {
            Monitor.Pulse(_threadLock);
        }
    }
    

提交回复
热议问题