0

我有一个线程正在调用两个单独的线程来做一些工作。每当任何工作完成时,都会调用 Waithandle.Set(0 并且在父工作线程结束时,我想 WaitAll 让两者都完成,然后再继续。但是 priceA() 仍然首先出现,然后是 PriceB ()。

new Thread(() =>
                           {
                               new Thread(() =>
                               {
                                   PriceA = _service.GetPriceA();
                                   _waithandle[0].Set();
                               }).Start();

                               new Thread(() =>
                               {
                                   PriceB = _service.GetPriceB();
                                   _waithandle[1].Set();
                               }).Start();

                               WaitHandle.WaitAll(_waithandle);
                           }).Start();
Console.WriteLine("Hello");

我错过了什么?

更新:

private EventWaitHandle[] _waithandle;

托儿:

 _waithandle[0] = new ManualResetEvent(false);
 _waithandle[1] = new ManualResetEvent(false);
4

3 回答 3

4

您正在创建一个单独的线程来等待......但是您给出的语句之后的代码将继续,因为您没有在线程中等待。换句话说,您正在创建三个线程:

  • 线程 X:创建线程 A 和 B,然后等待它们完成
  • 线程 A:获取 PriceA 然后设置 waitHandle[0]
  • 线程 B:获取 PriceB 然后设置 waitHandle[1]

但是线程 X 在等待之后什么都不做,那么在其中等待有什么意义呢?

此外,仅调用Join您创建的额外线程会简单得多。实际上,如果您只需要在“当前”线程中等待,那么您首先只需要一个额外的线程:

Thread t = new Thread(() => { PriceA = _service.GetPriceA(); });
t.Start();
PriceB = _service.GetPriceB();
t.Join();
// Other code

当您到达“其他代码”时,PriceA 和 PriceB 都已设置。当然,这缺少大量的错误处理......但是当你有一个比你当前过于复杂的代码更简单的起点时,它更容易添加。

于 2011-02-19T10:40:09.360 回答
0

您是否正确重置_waithandle[0]and [1]?例如:

_waithandle[0] = new ManualResetEvent(false);
_waithandle[1] = new ManualResetEvent(false);
于 2011-02-19T10:35:04.250 回答
0
new Thread(() =>
                           {
                               new Thread(() =>
                               {
                                   _priceA = _service.GetPriceA();
                                   _waithandle[0].Set();
                               }).Start();

                               new Thread(() =>
                               {
                                   _priceB = _service.GetPriceB();
                                   _waithandle[1].Set();
                               }).Start();

                               WaitHandle.WaitAll(_waithandle);
                               PriceA = _priceA;
                               PriceB = _priceB;
                           }).Start();

这为我完成了工作。罪魁祸首是 PriceA 和 PriceB 的 INotifyChangedProperty() 过早更新 UI,使我的 waitall 变得多余。万一其他人有类似的问题......

于 2011-02-19T10:51:27.067 回答