我写了一个线程池,如何使用它来通知已完成任务的方法?

Fug*_*ugu 2 c# multithreading delegates threadpool

所以我想说我有一个方法,比如ThreadPool.QueueTask(Delegate d).

其中一些委托需要返回值,但由于它们无法执行此操作(作为委托传递),因此需要通过引用将值作为参数.任务完成后,该值将被更改,因此调用方法需要知道这一点.

本质上,将任务传递给线程池的方法应该等到它完成.

做这个的最好方式是什么?我应该只做Threadpool.QueueTask(Delegate d,EventWaitHandle e),还是有更优雅的方式对于那些不熟悉这种事情的人来说是显而易见的?

亲切的问候,府谷

Kir*_*ril 6

您可以使用ManualResetEvent:

public void TaskStartMethod()
{
    ManualResetEvent waitHandle = new ManualResetEvent(false);

    ThreadPool.QueueUserWorkItem(o=>
    {
        // Perform the task here

        // Signal when done
        waitHandle.Signal();
    });

    // Wait until the task is complete
    waitHandle.WaitOne();
}
Run Code Online (Sandbox Code Playgroud)

本质上,将任务传递给线程池的方法应该等到它完成.

上面的代码可以做到这一点,但现在我有一个问题:如果你的方法正在等待任务完成,那么为什么你甚至懒得在一个单独的线程上执行任务呢?换句话说,你所描述的是代码的顺序执行而不是并行,所以使用它ThradPool是没有意义的.

或者,您可能希望使用单独的委托作为回调:

public delegate void OnTaskCompleteDelegate(Result someResult);

public void TaskStartMethod()
{
    OnTaskCompleteDelegate callback = new OnTaskCompleteDelegate(OnTaskComplete);
    ThradPool.QueueUserWorkItem(o=>
    {
        // Perform the task

        // Use the callback to notify that the
        // task is complete. You can send a result
        // or whatever you find necessary.
        callback(new Result(...));
    });

}

public void OnTaskComplete(Result someResult)
{
    // Process the result
}
Run Code Online (Sandbox Code Playgroud)

更新(2011年1月24日): 您可能甚至不需要回调委托,您可以直接调用OnTaskComplete,也应该完成这项工作:

public void TaskStartMethod()
{
    ThradPool.QueueUserWorkItem(o=>
    {
        // Perform the task

        // Call the method when the task is complete
        OnTaskComplete(new Result(...));
    });
}
Run Code Online (Sandbox Code Playgroud)