c# - 退出没有循环的线程

标签 c# multithreading concurrency thread-safety io-completion-ports

我需要一种方法来停止不包含循环的工作线程。应用程序启动线程,然后线程创建一个 FileSystemWatcher 对象和一个 Timer 对象。其中每一个都有回调函数。 到目前为止,我所做的是向线程类添加一个volatile bool 成员,并使用定时器来检查这个值。一旦设置了这个值,我就挂断了如何退出线程。

    protected override void OnStart(string[] args)
    {
      try
      {
        Watcher NewWatcher = new Watcher(...);
        Thread WatcherThread = new Thread(NewWatcher.Watcher.Start);
        WatcherThread.Start();
      }
      catch (Exception Ex)
      {
          ...
      }
    }

public class Watcher
{
    private volatile bool _StopThread;

    public Watcher(string filePath)
    {
        this._FilePath = filePath;
        this._LastException = null;

        _StopThread = false;
        TimerCallback timerFunc = new TimerCallback(OnThreadTimer);
        _ThreadTimer = new Timer(timerFunc, null, 5000, 1000);
    }   

    public void Start()
    {
        this.CreateFileWatch();            
    }

    public void Stop()
    {
        _StopThread = true;
    }

    private void CreateFileWatch()
    {
        try
        {
            this._FileWatcher = new FileSystemWatcher();
            this._FileWatcher.Path = Path.GetDirectoryName(FilePath);
            this._FileWatcher.Filter = Path.GetFileName(FilePath);
            this._FileWatcher.IncludeSubdirectories = false;
            this._FileWatcher.NotifyFilter = NotifyFilters.LastWrite;
            this._FileWatcher.Changed += new FileSystemEventHandler(OnFileChanged);

            ...

            this._FileWatcher.EnableRaisingEvents = true;
        }
        catch (Exception ex)
        {
            ...
        }
    }

    private void OnThreadTimer(object source)
    {
        if (_StopThread)
        {
            _ThreadTimer.Dispose();
            _FileWatcher.Dispose();
            // Exit Thread Here (?)
        }
    }

    ...
}

所以我可以在线程被告知停止时处理 Timer/FileWatcher - 但我如何实际退出/停止线程?

最佳答案

我建议使用 ManualResetEvent,而不是 bool 标志。线程启动 FileSystemWatcher,然后等待一个事件。当调用 Stop 时,它会设置事件:

private ManualResetEvent ThreadExitEvent = new ManualResetEvent(false);

public void Start()
{
    // set up the watcher
    this.CreateFileWatch();

    // then wait for the exit event ...
    ThreadExitEvent.WaitOne();

    // Now tear down the watcher and exit.
    // ...
}

public void Stop()
{
    ThreadExitEvent.Set();
}

这样您就不必使用计时器,而且您仍会收到所有通知。

关于c# - 退出没有循环的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5623113/

相关文章:

C# 'ref' 关键字,性能

c# - 在 WCF Webapi 站点上验证 Android 客户端?

c# - U-SQL 将一列拆分为两列,由 "-"分隔

multithreading - 更快的 TMultiReadExclusiveWriteSynchronizer?

c++ - SLX 云是否允许自定义库?

java - 从辅助线程在主线程上运行代码?

c# - 未调用 DropCreateDatabaseAlways 种子

java - 如何在多线程JAVA环境中保护对象而不损失性能?

c++ - 在什么情况下无锁数据结构比基于锁的数据结构更快?

java - 同步块(synchronized block)可以比 Atomics 更快吗?