检测到一个线程池工作项目已经完成/等待完成 [英] Detecting that a ThreadPool WorkItem has completed/waiting for completion

查看:132
本文介绍了检测到一个线程池工作项目已经完成/等待完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

无论出于何种原因,的 QueueWorkItem 不返回线程池 IAsyncResult的或一些其他句柄工作项目,这将使等到它完成。有 RegisterWait ... 方法,但你必须通过一个的WaitHandle 和创造他们的是昂贵的(见的IAsyncResult 文档,建议您延迟创建一个的WaitHandle ,直到请求)。任务并行库将解决缺乏,但有一个漫长的等待这是可用之前。那么,有没有这种设计的任何问题:

For whatever reason, ThreadPool's QueueWorkItem doesn't return an IAsyncResult or some other handle to the work item, which would allow to wait until it's completed. There are RegisterWait... methods, but you have to pass a WaitHandle and creating them is expensive (see IAsyncResult documentation, which advises you to delay creating a WaitHandle until requested). The Task Parallel Library will fix this lack, but there is a long wait before that's available. So, are there any problems with this design:

public class Concurrent<T> {
    private ManualResetEvent _resetEvent;
    private T _result;

    public Concurrent(Func<T> f) {
        ThreadPool.QueueUserWorkItem(_ => {
                                         _result = f();
                                         if (_resetEvent != null)
                                             _resetEvent.Set();
                                     });
    }

    public WaitHandle WaitHandle {
        get {
            if (_resetEvent == null)
                _resetEvent = new ManualResetEvent(_result != null);
            return _resetEvent;
        }

    ...

编辑:
我问了一个<一个href=\"http://stackoverflow.com/questions/406915/using-begininvoke-endinvoke-in-a-multithreaded-fashion-how-do-asynccallback-asy\">follow-up有关使用替代线程池异步委托其时出现的问题的担忧。

I asked a follow-up question about the concerns which arise when using async delegates instead of the ThreadPool.

推荐答案

好了,你有在获取的WaitHandle并将它设置之间的竞争条件。你真的想调用者永远等待,如果他们碰巧是一个很小的有点晚了?

Well, you've got a race condition between fetching the WaitHandle and setting it. Do you really want the caller to be waiting forever if they happen to be a tiny bit late?

您或许应该做一些适当的锁定,并保持一个我已经完成了标志,这样,如果你的的创建WaitHandle的它完成后,你返回之前设置它。

You should probably do some appropriate locking and keep an "I've finished" flag so that if you do create the WaitHandle after it's finished, you set it before returning it.

我也亲自执笔的静态工厂方法,而不是只使用一个公共的构造函数 - 或者使之成为创建和的然后的显式启动的格局。在构造函数中排队的工作项目感觉怪怪的我。

I'd also personally write a static factory method rather than just using a public constructor - or make it a "create and then explicitly start" pattern. Queuing the work item in the constructor feels weird to me.

这篇关于检测到一个线程池工作项目已经完成/等待完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆