简体   繁体   English

WaitHandle.WaitAll和ManualResetEvent.Set()-首先应该是什么?

[英]WaitHandle.WaitAll and ManualResetEvent.Set() - what should be first?

I have a question about working of WaitHandle.WaitAll, and would appreciate any help. 我对WaitHandle.WaitAll的工作有疑问,希望能对您有所帮助。

Let's assume I have such situation: the Parent thread is opening couple of Child Threads and must wait with 'doing other stuff' until child threads finish their work. 假设我有这种情况:父线程正在打开几个子线程,并且必须等待“做其他事情”,直到子线程完成其工作。

I use WaitHandle.WaitAll and would like to stay with this method. 我使用WaitHandle.WaitAll,并希望继续使用此方法。 (NO Thread.Join etc, please :) ) (没有Thread.Join等,请:))

ManualResetEvent[] events = new ManualResetEvent[list.Count];

foreach (string row in list)
{
    events[i] = new ManualResetEvent(false);                

    Thread thread = new Thread(new ParameterizedThreadStart(DoSomething));
    thread.Start(events[i]); // start child thread

    System.Threading.Thread.Sleep(1000000);

    i++;
}

WaitHandle.WaitAll(events); // wait for child threads finish their work
...
...


private DoSomething(object sth)
{
// some stuff that executes only 1 second
ManualResetEvent.Set()
}

So situation for the first newly started child-thread would be that the calling of ManualResetEvent.Set() is BEFORE calling WaitHandle.WaitAll(events) in the Parent thread. 因此,第一个新启动的子线程的情况是,在父线程中调用ManualResetEvent.Set()之前先调用WaitHandle.WaitAll(events)。 Because loop which opens new child threads has some long timeout. 因为打开新的子线程的循环超时时间较长。

So my question, wouldn't be such time-line a problem? 所以我的问题是,这样的时间表不会成为问题吗? Shouldn't be WaitHandle.WaitAll called before calling the ManualResetEvent.Set()? 在调用ManualResetEvent.Set()之前不应该调用WaitHandle.WaitAll吗?

It does not matter. 不要紧。 The wait returns when all events are signaled (set) - whether or not that happened before or after wait was called. 当所有事件都被信号通知(设置)时,等待返回-无论该事件是在调用等待之前还是之后发生的。

As it was said, it does not matter, however, you should consider using the Task class for that kind of things. 如前所述,这没关系,但是,您应该考虑将Task类用于此类事情。

It also allows you to run your tasks either simultaneously or consequentially. 它还允许您同时或依次运行任务。

Your code then will be only this: 然后,您的代码将仅仅是这样:

Task.WaitAll(
    Task.Factory.StartNew(() =>
    {
        Thread.Sleep(1000);
    }),
    Task.Factory.StartNew(() => { Thread.Sleep(1000); }),
    Task.Factory.StartNew(() => { Thread.Sleep(1000); })
    );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM