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.

    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?

Answers


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.


Need Your Help

Regarding Big Decimal

java double bigdecimal

I have a csv file where amount and quantity fields are present in each detail record except header and trailer record. Trailer record has a total charge values which is the total sum of quantity

Breakpoint not hitting on ItemDataBound function

c# asp.net telerik radgrid

I have a grid control called RadGrid1 and with a breakpoint in RadGrid1_ItemDataBound, but when I run my aspx application, the breakpoint is not being triggered.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.