Created
November 2, 2017 12:12
-
-
Save Cassandra-d/47e53662d3b2a6ca1c5be4a47eb1c093 to your computer and use it in GitHub Desktop.
Example of waiting for several threads to complete
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Program | |
{ | |
private static Thread one; | |
private static Thread two; | |
private static Thread three; | |
private static HybridDictionary events; | |
static void Main(string[] args) | |
{ | |
events = new HybridDictionary(); | |
one = new Thread(Action); | |
two = new Thread(Action); | |
three = new Thread(Action); | |
one.Start(1); | |
two.Start(2); | |
three.Start(3); | |
var cts = new CancellationTokenSource(); | |
var ct = cts.Token; | |
Task.Factory.StartNew(() => | |
{ | |
bool completed = false; | |
while (!ct.IsCancellationRequested && !completed) | |
{ | |
completed = | |
WaitHandle.WaitAll( | |
events.Values.Cast<ManualResetEvent>().ToArray(), | |
TimeSpan.FromSeconds(1)); | |
} | |
if (completed) | |
Console.WriteLine("Changed!"); | |
}); | |
Console.ReadKey(); | |
} | |
public static void Action(object id) | |
{ | |
var ev = new ManualResetEvent(false); | |
events[id] = ev; | |
Thread.Sleep(2000 * (int)id); | |
ev.Set(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment