您可以使用Interlocked.CompareExchange
設定中獎線:
static Thread winner = null;
private static void MyFunc()
{
Thread.Sleep((int)(new Random().NextDouble() * 1000));
Interlocked.CompareExchange(ref winner, Thread.CurrentThread, null);
}
public static void Main()
{
Thread thread1 = new Thread(() => MyFunc());
Thread thread2 = new Thread(() => MyFunc());
Thread thread3 = new Thread(() => MyFunc());
thread1.Name = "thread1";
thread2.Name = "thread2";
thread3.Name = "thread3";
thread1.Start();
thread2.Start();
thread3.Start();
thread1.Join();
thread2.Join();
thread3.Join();
Console.WriteLine("The winner is {0}", winner.Name);
}
Live Demo
UPDATE:如果你不希望所有線程完成你檢查之前,存在使用更簡單的方法AutoResetEvent
S和WaitHandle.WaitAny()
:
private static void MyFunc(AutoResetEvent ev)
{
Thread.Sleep((int)(new Random().NextDouble() * 1000));
ev.Set();
}
public static void Main()
{
AutoResetEvent[] evs = {new AutoResetEvent(false), new AutoResetEvent(false), new AutoResetEvent(false)};
Thread thread1 = new Thread(() => MyFunc(evs[0]));
Thread thread2 = new Thread(() => MyFunc(evs[1]));
Thread thread3 = new Thread(() => MyFunc(evs[2]));
thread1.Start();
thread2.Start();
thread3.Start();
int winner = WaitHandle.WaitAny(evs);
Console.WriteLine("The winner is thread{0}", winner + 1);
}
Live Demo
是否可以切換到'Task'而不是'Thread'?任務具有使這種簡單的類(['Task.WhenAny'](http://msdn.microsoft.com/zh-cn/library/system.threading.tasks.task.whenany(v = vs.110).aspx )) – 2014-09-11 13:22:23
Scott,在框架4.0中可以嗎? – Sam 2014-09-11 13:23:57
如果您需要知道哪個線程先完成,請返回到繪圖板。如果兩個線程同時完成會怎麼樣?重要的時候我無法想到一個情況。 [這樣做的目的是什麼?](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) – 2014-09-11 13:24:58