Capture .Net Thread End Event

I would like an elegant way to capture the end / exit event of a stream. So far I have found two approaches:

  • Use a background worker that has a RunWorkerCompleted event, or
  • My workflow will explicitly call the delegate "I am leaving."

Yes, they will work, but there must be some way from the parent thread (the thread that calls the Thread.Start () method) in order to detect when the thread exited regardless of why, how, and when. For example, the Visual Studio debug output window tells you when threads are ending:, "Thread 0x1454 exited with code 0 (0x0)." Therefore, it should be possible.

Thanks in advance for any ideas!

+3
source share
4

Windows Forms, Application.ThreadExit .

( , , , ), . , .

+3
+1

thread.join(), , com sendMessage.

Thread t = new Thread (delegate() { Console.ReadLine(); });

t.Start();

t.Join();    // Wait until thread t finishes

Console.WriteLine ("Thread t ReadLine complete!");
+1

- :

I would use option 2 in a slightly modified way. Use ManualResetEvent (or AutoResetEvent), and let the parent thread wait for your thread to exit using the WaitOne method.

using(ManualResetEvent completed = new ManualResetEvent(false))
{

var thread = new Thread(new ThreadStart(delegate()
{
    try
    {
        // do work here
    }
    finally
    {
        completed.Set();
    }

}));

// start thread
thread.Start();


// wait until thread is completed
completed.WaitOne();
}

You can also use Thread.Join (), which AndrewB offers, but I prefer ManualResetEvent, since it gives you more control over how and when it called.

0
source

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


All Articles