How to terminate a worker thread correctly in c#

后端 未结 4 1681
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-15 23:36

Problem statement

I have a worker thread that basically scans a folder, going into the files within it, and then sleeps for a while. The scanning operat

4条回答
  •  旧时难觅i
    2021-02-16 00:04

    Another alternative is to use events:

    private ManualResetEvent _event = new ManualResetEvent(false);
    
    
    public void Run() 
    {
     while (true)
     {
        DoSomethingThatTakesSeveralSeconds();
        if (_event.WaitOne(timeout))
          break;
     }
    }
    
    public void Stop() 
    {
       _event.Set();
       thread.Join();
    }
    

提交回复
热议问题