Is there a way to check what works in the .NET thread pool?

I usually created each thread for an action that I wanted to do multithreaded. I did it like this:

private Thread threadForWycena;

private void someMethod() {
       threadForWycena = new Thread(globalnaWycena);
       threadForWycena.Start();
}

Then, when the user wanted to close one of the gui, I checked this thread, and if it was on i, he was disappointed 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 this with ThreadPool so that I can prevent the window from closing and I can tell the user which thread is still alive and what it is doing?

+3
source share
2 answers

There is no direct way to determine when a work item in a thread pool was completed in .NET. However, it is not difficult to add it.

  • Create ManualResetEvent
  • At the end of the work item, set this event.
  • , , , , .

. ( 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
}

, .NET 4 Task ( ) threadpool, .

+3

Source: https://habr.com/ru/post/1734842/


All Articles