加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 使用TPL实现经典异步模式

发布时间:2020-12-15 06:23:58 所属栏目:百科 来源:网络整理
导读:我正在尝试为WF 4实现一个CustomParticipator.我可以编写Track方法,但是我的实现会很慢. 如何使用.NET 4.0的任务并行库(TPL)实现Begin / EndTrack覆盖?我看过TPL and Traditional .NET Asynchronous Programming,但不知道如何在这里应用. 请注意,TrackingPa
我正在尝试为WF 4实现一个CustomParticipator.我可以编写Track方法,但是我的实现会很慢.

如何使用.NET 4.0的任务并行库(TPL)实现Begin / EndTrack覆盖?我看过TPL and Traditional .NET Asynchronous Programming,但不知道如何在这里应用.

请注意,TrackingParticipant是.NET的一部分,并使用虚拟方法预定义了“经典异步模式”.

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
    }
}

解决方法

这是实现经典APM编程模型的通用模式:
protected override IAsyncResult BeginTrack(TrackingRecord record,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方法返回一个结果,你实际上将返回任务的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;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读