繁体   English   中英

使用基于事件的异步模式时,如何让主线程等待其他线程?

[英]How do I have the main thread wait for other threads when using the Event-based Asynchronous Pattern?

我有一个主线程,通过一个实现基于事件的异步模式的类( http://msdn.microsoft.com/en-us/library/ms228969.aspx )启动一些工作线程。 不幸的是,只要主线程完成设置工作线程,它就会退出。

我希望主线程无限期地等待,直到调用anEventHandler方法,然后处理该方法。 asyncevents无限期地监听事件直到被取消,因此他们可能在完成之前多次调用anEventHandler方法。

注意:没有相关的GUI,我只是使用这种模式。

   public static void Main(String[] args) {
        AsyncEventClass asyncevent = new AsyncEventClass();

        // setup event handling
        asyncevent.Events += new EventsHandler(anEventHandler);

        // start event monitoring threads
        asyncevent.monitorAsync(1);
        asyncevent.monitorAsync(2);
        asyncevent.monitorAsync(3);

        System.Console.WriteLine("The main thread now ends. :(");
    }

所有在线示例都使用System.Console.ReadLine() ,但这在生产代码中似乎是个糟糕的主意。

您可以使用在main方法中等待的简单AutoResetEvent ,并在事件处理程序中设置。

如果你想等待调用事件处理程序的特定次数,我猜你可以保留一个计数器,并且只有当你达到某个阈值时才设置自动重置事件。

我最后通过调用WorkerEventHandler.BeginInvoke将所有返回的IAsyncResutl对象放入一个列表中,然后将该列表公开给Main方法。 在那里,我设置了我需要监听的所有asyncevents,然后使用WaitHandle.WaitAll等待事件完成。

暂无
暂无

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

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