有没有办法检查 .NET 线程池中正在运行的内容?
通常,我会为每个我想要执行多线程的操作创建每个线程。我是这样做的:
private Thread threadForWycena;
private void someMethod() {
threadForWycena = new Thread(globalnaWycena);
threadForWycena.Start();
}
然后,当用户想要关闭其中一个 gui 时,我正在检查该线程,如果它处于打开状态,我将不允许关闭它。
private void ZarzadzajOplatamiGlobalneDzp_FormClosing(object sender, FormClosingEventArgs e)
{
if (threadForWycena.IsAlive) {
MessageBox.Show("Wycena jest w toku. Zamknięcie okna jest niemożliwe.", "Brak wyjścia :-)");
e.Cancel = true;
}
}
有没有办法使用 ThreadPool 来做到这一点,以便我可以防止窗口关闭,并且可以告诉用户哪个线程仍然存在以及它在做什么?
Normally i was creating each thread per action i wanted to do multithreaded. I was doing it like that:
private Thread threadForWycena;
private void someMethod() {
threadForWycena = new Thread(globalnaWycena);
threadForWycena.Start();
}
Then when user wanted to close one of the gui's i was checking for this thread and if it was on i was dissalowing to close it.
private void ZarzadzajOplatamiGlobalneDzp_FormClosing(object sender, FormClosingEventArgs e)
{
if (threadForWycena.IsAlive) {
MessageBox.Show("Wycena jest w toku. Zamknięcie okna jest niemożliwe.", "Brak wyjścia :-)");
e.Cancel = true;
}
}
Is there a way to do it using ThreadPool, so that i can prevent window closing and i can tell user which thread is still alive and what's it's doing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 .NET 中,没有直接的方法可以检测线程池工作项何时完成。不过,添加一个并不难。
ManualResetEvent
例如(使用 lambda 关闭事件并避免修改要在线程池中运行的代码):
顺便说一句,在 .NET 4 中,Task 类(和子类型)提供了更丰富的模型来在线程池中运行代码,包括能够直接返回结果,或继续另一项任务。
There is no direct way to detect when a thread pool work item has completed in .NET. However it is not hard to add one.
ManualResetEvent
E.g. (using a lambda to close over the event and avoid modifying the code to run in the threadpool):
By the way, in .NET 4 the Task class (and subtypes) provides a much richer model to run code in the threadpool, including ability to directly return results, or continue with another task.
RegisterWaitForSingleObject 将向等待句柄发出信号执行完毕。
RegisterWaitForSingleObject will signal the wait handle when it finishes executing.