Csharp/C#教程:使用TPL实现经典异步模式分享


使用TPL实现经典异步模式

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

如何使用.NET 4.0的任务并行库(TPL)实现Begin / EndTrack覆盖? 我看过TPL和Traditional .NET异步编程,但我不知道如何在这里应用它。

请注意,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, 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方法返回结果,您实际上将返回TaskResult属性,而不是仅调用Wait 。 例如:

上述就是C#学习教程:使用TPL实现经典异步模式分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

 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)asyncResult).Result; } 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/999702.html

(0)
上一篇 2021年12月27日
下一篇 2021年12月27日

精彩推荐