使用TPL实现经典异步模式

10

我正在尝试为WF 4实现自定义TrackingParticipant。我可以编写Track方法,但是我的实现会很慢。

如何使用.NET 4.0的任务并行库(TPL)实现Begin/EndTrack重写?我已经查看了TPL和传统的.NET异步编程,但不确定如何在此处应用它。

请注意,TrackingParticipant是.NET的一部分,并且具有使用虚拟方法预定义的Classic异步模式。

public class MyTrackingParticipant : TrackingParticipant
{
    protected override IAsyncResult BeginTrack(
        TrackingRecord record, TimeSpan timeout,
        AsyncCallback callback, object state)
    {
        // ?
    }

    protected override void EndTrack(IAsyncResult result)
    {
        // ?
    }

    protected override void Track(TrackingRecord record, TimeSpan timeout)
    {
        // synchronous code to be called
    }
}
1个回答

17

以下是实现经典APM编程模型的通用模式:

protected override IAsyncResult BeginTrack(TrackingRecord record, TimeSpan timeout, AsyncCallback callback, object state)
{
    Task result = Task.Factory.StartNew(
        (taskState) =>
        {
           // ... your async work here ...
        },
        state);

    if(callback != null)
    {
        result.ContinueWith((t) => callback(t));
    }

    return result;
}

protected override void EndTrack(IAsyncResult asyncResult)
{
   // Call wait to block until task is complete and/or cause any exceptions that occurred to propagate to the caller
   ((Task)asyncResult).Wait();
}

如果EndXXX方法返回了结果,你实际上应该返回Task的Result属性而不仅仅是调用Wait方法。例如:
protected override int EndAwesomeCalculation(IAsyncResult asyncResult)
{
   // This will block until the result is available and/or cause any exceptions that occurred propagate to the caller
   return ((Task<int>)asyncResult).Result;
}

谢谢!这个有效;奇怪的是,工作流仍然会阻塞,直到Track()完成。(它确实调用了Begin/End方法。)看起来我需要实现一个队列来获得我想要的行为。(不是为了减少你正确的答案的价值!) - TrueWill

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接