views:

126

answers:

2

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?

+1  A: 

RegisterWaitForSingleObject will signal the wait handle when it finishes executing.

Darin Dimitrov
And how would one use it properly considering example i gave?
MadBoy
+2  A: 

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.

Richard
So it's actually harder then by using it without pool. Just wonder if it will look 'lame' to use many `private Thread threadForWycena;` (of course with different name instead of a pool. It's easier for me to actually know what's going on, what is running and what is not. Usually the feature being run is not gonna be run again until the old one finishes.
MadBoy