Threads that return data in .NET
c#, multithreading
Solution
Use a `WaitHandle`
Here's an example:
using System;
using System.Threading;
class ThreadSleeper
{
int seconds;
AutoResetEvent napDone = new AutoResetEvent(false);
private ThreadSleeper(int seconds)
{
this.seconds = seconds;
}
public void Nap()
{
Console.WriteLine("Napping {0} seconds", seconds);
Thread.Sleep(seconds * 1000);
Console.WriteLine("{0} second nap finished", seconds);
napDone.Set();
}
public static WaitHandle DoSleep(int seconds)
{
ThreadSleeper ts = new ThreadSleeper(seconds);
Thread thread = new Thread(new ThreadStart(ts.Nap));
thread.Start();
return(ts.napDone);
}
}
public class OperationsThreadsWaitingwithWaitHandle
{
public static void Main()
{
WaitHandle[] waits = new WaitHandle[2];
waits[0] = ThreadSleeper.DoSleep(8);
waits[1] = ThreadSleeper.DoSleep(4);
Console.WriteLine("Waiting for threads to finish");
WaitHandle.WaitAll(waits);
Console.WriteLine("Threads finished");
}
}
Links to check out:
- Threads:Waiting with WaitHandle
- Jon Skeet's post
- Difference between Barrier in C# 4.0 and WaitHandle in C# 3.0?
- Novice C# threading: WaitHandles
- WaitHandle Exceptions and Work Arounds
- Multithreading with C#
- WaitHandle, AutoResetEvent and ManualResetEvent Classes in VB.Net
Problem
I'm writing a program where I typically start five threads. The threads return in a non-determinate order. Each thread is calling a method which returns a List. I'm doing this: ``` var masterList = List<string>(); foreach (var threadParam in threadParams) { var expression = threadParam ; ThreadStart sub = () => MyMethod(expressions); var thread = new Thread(sub) { Name = expression }; listThreads.Add(thread); thread.Start(); } var abort = true; while (abort) //Wait until all threads finish { var count = 0; foreach (var list in listThreads) { if (!list.IsAlive) { count++; } } if (count == listThreads.Count) { abort = false; } } ``` So here is the problem: Each thread when it terminates returns a list I would like to append the masterList declared earlier. How would one go about this? Also I KNOW there must be a better way than below to wait for all threads to finish ``` var abort = true; while (abort) //Wait until all threads finish { var count = 0; foreach (var list in listThreads) { if (!list.IsAlive) { count++; } } if (count == listThreads.Count) { abort = false; } } ```