Languages
[Edit]
EN

C#/.NET - wait for thread to finish

7 points
Created by:
JustMike
3488

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
Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.