Languages
[Edit]
EN

C#/.NET - wait for thread to finish

7 points
Created by:
Nabila-Burnett
385

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
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

C# - Thread Class

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join