gpt4 book ai didi

c# - 是否有可能知道哪个线程先完成?

转载 作者:行者123 更新时间:2023-11-30 17:46:45 27 4
gpt4 key购买 nike

如果我有 3 个线程。是否有可能知道哪个线程先完成。

一些示例代码

    Thread thread1 = new Thread(() => MyFunc());
Thread thread2 = new Thread(() => MyFunc());
Thread thread3 = new Thread(() => MyFunc());

thread1.Start();
thread2.Start();
thread3.Start();

while (thread1.IsAlive || thread2.IsAlive || thread3.IsAlive)
{
//I need condition to which thread dead first.
}

最佳答案

您可以使用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

更新:如果您不希望所有线程在您检查之前完成,可以使用 AutoResetEventWaitHandle.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

关于c# - 是否有可能知道哪个线程先完成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25788560/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com