[英]Is there a way to check what's running in the .NET Thread Pool?
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. 然后,当用户想要关闭其中一个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;
}
}
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? 有没有办法使用ThreadPool,这样我可以阻止窗口关闭,我可以告诉用户哪个线程仍然活着,它在做什么?
There is no direct way to detect when a thread pool work item has completed in .NET. 没有直接的方法来检测线程池工作项何时在.NET中完成。 However it is not hard to add one.
但是添加一个并不难。
ManualResetEvent
ManualResetEvent
Eg (using a lambda to close over the event and avoid modifying the code to run in the threadpool): 例如(使用lambda来关闭事件并避免修改代码以在线程池中运行):
var e = new ManualResetEvent(false); // false => not set to sart
ThreadPool.QueueUserWorkItem(_ => { FunctionToCall(); e.Set(); });
// Continue concurrently....
if (e.WaitOne(0)) {
// The work item has completed
}
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. 顺便说一句,在.NET 4中,Task类(和子类型)提供了一个更丰富的模型来运行线程池中的代码,包括直接返回结果或继续执行其他任务的能力。
RegisterWaitForSingleObject将在完成执行时发出等待句柄的信号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.