C# 等待两个线程完成

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/594230/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 09:36:28  来源:igfitidea点击:

Wait for two threads to finish

c#multithreading

提问by Boris Callens

If you have one main thread that starts two other threads. what is the cleanest way to make the primary thread wait for the two other threads?

如果您有一个主线程启动另外两个线程。使主线程等待其他两个线程的最干净方法是什么?

I could use bgndworker and sleep spinner that checks for both the bgnd workers's IsBusy, but I would think there's a better way.

我可以使用 bgndworker 和 sleep spinner 来检查 bgnd 工人的 IsBusy,但我认为有更好的方法。

EDITSome more requirements:

编辑一些更多的要求:

  • The main thread has some other work to do (e.g. GUI).
  • The two spawned threads should be able to report exceptions and return result values
  • 主线程还有一些其他工作要做(例如 GUI)。
  • 两个衍生的线程应该能够报告异常并返回结果值

采纳答案by Marc Gravell

See the answers on this thread. I like this option;-p

请参阅此线程上的答案。我喜欢这个选项;-p

Forker p = new Forker();
p.Fork(delegate { DoSomeWork(); });
p.Fork(delegate { DoSomeOtherWork(); });
p.Join();

Re returning values / reporting exceptions - just have each fork do that as a callback at the end of the logic... (you can use captured variables to pass state into both the forks, including a shared logger etc).

重新返回值/报告异常 - 只需让每个叉子在逻辑结束时作为回调来执行……(您可以使用捕获的变量将状态传递到两个叉子中,包括共享记录器等)。

回答by Erik Funkenbusch

WaitHandle.WaitAny is your friend. It lets you wait on multiple threads or other kinds of objects to be signaled.

WaitHandle.WaitAny 是您的朋友。它允许您等待多个线程或其他类型的对象发出信号。

http://msdn.microsoft.com/en-us/library/tdykks7z.aspx

http://msdn.microsoft.com/en-us/library/tdykks7z.aspx

EDIT:

编辑:

Actually, WaitHandle.WaitAll is what you want, not WaitAny.

实际上,WaitHandle.WaitAll 是您想要的,而不是 WaitAny。

http://msdn.microsoft.com/en-us/library/system.threading.waithandle.waitall.aspx

http://msdn.microsoft.com/en-us/library/system.threading.waithandle.waitall.aspx

EDIT:

编辑:

The Join method some mention is ok, but one drawback is that it's not an completely atomic operation. This may or may not be important to you, though.

有些人提到的 Join 方法是可以的,但一个缺点是它不是一个完全原子的操作。不过,这对您来说可能重要也可能不重要。

回答by James L

thread1.Join();
thread2.Join();

回答by REA_ANDREW

Quick example using Thread.Join();

使用 Thread.Join() 的快速示例;

        Thread t1 = new Thread(new ThreadStart(delegate()
        {
            System.Threading.Thread.Sleep(2000);
        }));

        Thread t2 = new Thread(new ThreadStart(delegate()
        {
            System.Threading.Thread.Sleep(4000);
        }));

        t1.Start();
        t2.Start();

        t1.Join();
        t2.Join();

EDIT Another 3example using Wait Handles:

编辑另一个 3example 使用等待句柄:

            ManualResetEvent[] waitHandles = new ManualResetEvent[]{
            new ManualResetEvent(false),
            new ManualResetEvent(false)
        };

        Thread t1 = new Thread(new ParameterizedThreadStart(delegate(object state)
        {
            ManualResetEvent handle = (ManualResetEvent)state;
            System.Threading.Thread.Sleep(2000);
            handle.Set();
        }));

        Thread t2 = new Thread(new ParameterizedThreadStart(delegate(object state)
        {
            ManualResetEvent handle = (ManualResetEvent)state;
            System.Threading.Thread.Sleep(4000);
            handle.Set();
        }));

        t1.Start(waitHandles[0]);
        t2.Start(waitHandles[1]);

        WaitHandle.WaitAll(waitHandles);

        Console.WriteLine("Finished");

回答by Jon Skeet

In addition to the other answers... one alternative to "start two threads and wait for both to finish" is "start onethread and do one job yourself, then wait for the other thread to finish".

除了其他答案......“启动两个线程并等待两个线程完成”的另一种选择是“启动一个线程并自己完成一项工作,然后等待另一个线程完成”。

Of course, if you want to start two jobs, do some more work on the main thread and thenwait for the two other threads to finish, that doesn't work so well.

当然,如果你想开始两个工作,在主线程上多做一些工作,然后等待另外两个线程完成,那效果不是很好。

EDIT: If the main thread is a UI thread, you shouldn't be blocking on the other threads finishing - you should (IMO) get them to call back to the main thread when they've finished. That way you'll still have a responsive UI while they're executing.

编辑:如果主线程是一个 UI 线程,你不应该阻塞其他线程完成 - 你应该(IMO)让它们在完成后回调到主线程。这样,您在执行时仍将拥有响应式 UI。

回答by Migol

You can't wait for finish and have GUI usable. The best approach for this is to spawn threads and use events to communicate with GUI. Remember, that in the event handler you cannot modify control. Rather that doing it directly, use Invoke method.

您迫不及待地等待完成并使用 GUI。最好的方法是产生线程并使用事件与 GUI 进行通信。请记住,在事件处理程序中您不能修改控件。与其直接做,不如使用 Invoke 方法。