在名为Worker的类中考虑以下代码
FileSystemWatcher watcher = new FileSystemWatcher();
public void Run()
{
watcher.Path = @"c:\queue";
watcher.Created += new FileSystemEventHandler(watcher_Created);
watcher.EnableRaisingEvents = true;
}
现在,这是我想对 worker 进行的操作,但是很明显,这不会实现。
Worker worker = new Worker();
Thread thread = new Thread(worker.Run);
thread.Start();
Console.ReadLine(); // something else more interesting would go here.
原因是Run方法结束而不是进入某种事件循环。我如何获得一个事件循环。 (我想我正在寻找类似Application.Run的东西)
最佳答案
未经测试,但是如果您希望“事件”循环在线程上运行,它将看起来像这样:
private bool running = true;
private AutoResetEvent waiter = new AutoResetEvent(false);
public void Run()
{
FileSystemWatcher watcher = new FileSystemWatcher("C:\\");
FileSystemEventArgs changes = null;
watcher.Changed +=
(object sender, FileSystemEventArgs e) => {
changes = e;
waiter.Set();
};
watcher.EnableRaisingEvents = true;
while (running)
{
waiter.WaitOne();
if (!running) break;
Console.WriteLine("Path: {0}, Type: {1}",
changes.FullPath, changes.ChangeType);
}
Console.WriteLine("Thread complete");
}
public void Stop()
{
running = false;
waiter.Set();
}
您可以将此代码放在一个类中,然后在单独的线程上运行(如果需要)。如果要让主线程在创建完成的线程上等待(尽管在这种情况下为什么还要麻烦创建一个线程?),则可以使用Thread.Join方法。
关于c# - 如何在第二个线程上等待事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1208560/