开发者

Is there a way to check what's running in the .NET Thread Pool?

开发者 https://www.devze.com 2022-12-21 08:15 出处:网络
Normally i was creating each thread per action i wanted to do multithreaded. I was doing it like that:

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 (thre开发者_如何学JAVAadForWycena.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?


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.

  • Create a ManualResetEvent
  • At the end of the work item set this event.
  • To check if the work item has completed perform a zero timeout wait on the event to see if it has been set.

E.g. (using a lambda to close over the event and avoid modifying the code to run in the threadpool):

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.


RegisterWaitForSingleObject will signal the wait handle when it finishes executing.

0

精彩评论

暂无评论...
验证码 换一张
取 消