Languages
[Edit]
EN

C#/.NET - wait for thread to finish

7 points
Created by:
JustMike
26120

In C#/.NET it is few ways to wait for thread finished.

1. Thread.Join method example

See this link.

2. Monitor.Pulse and Monitor.Wait example

using System;
using System.Threading;

namespace Test
{
	class Program
	{
		static void Main(string[] args)
		{
			Object locker = new Object();

			Thread thread = new Thread(() =>
			{
				Thread.Sleep(2000);

				lock (locker)
					Monitor.Pulse(locker);
			});

			thread.Start();

			lock(locker)
				Monitor.Wait(locker);

			Console.WriteLine("Thread job done...");
		}
	}
}

Output:

Thread job done...
Notes:
  1. Monitor.Wait and Monitor.Pulse methods should be called from lock block.
  2. Monitor.Wait method waits until Monitor.Pulse method is called.

References

  1. Thread Class - Microsoft Docs
  2. Monitor.Wait Method - Microsoft Docs
  3. Monitor.Pulse Method - Microsoft Docs
Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join