使用标准的.NET异步模式的优势是什么? [英] Advantages of using standard .Net Async patterns?

查看:143
本文介绍了使用标准的.NET异步模式的优势是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我设计一个执行长时间运行任务的类。我想出的第一个方案是:

I am designing a class that performs long running tasks. The first design I came up with was:

public TaskHandle DoSomethingAsync(DoSomethingCompleteCallback completedCallback);
public void       CancelDoSomething(TaskHandle handle);

这是简洁明了。不过,我想知道如果我要实现它作为标准的.NET异步模式我一直在读什么?一个

This is simple and concise. However, I am wondering if I should implement it as one of the standard .Net async patterns I have been reading about?

APM

public IAsyncResult BeginDoSomething(AsyncCallback completedCallback, Object stateObject);
public void         EndDoSomething(IAsyncResult asyncResult);

EAP:

public void  DoSomethingAsync(string param, object userState);
public event DoSomethingCompletedEventHandler DoSomethingCompleted;

IMO这些似乎对界面的不是被识别的模式向其他.NET开发人员等没有真正的好处复杂化。 APM要求客户端code总是调用EndDoSomething()甚至在其completedCallback和EAP需要单独订阅完成事件。

IMO these seem to complicate the interface for no real advantage other than being patterns recognisable to other .Net developers. APM requires client code to always call EndDoSomething() even in their completedCallback, and EAP requires separate subscription to the completed event.

有什么优势,如果有的话,使用,我很想念标准模式?

What are the advantages, if any, of using the standard patterns that I am missing?

推荐答案

这些模式的唯一好处是,他们立即识别给其他开发商,并可能有框架的支持(如开始WCF到底支持)。

The only advantages of these patterns is that they are instantly recognisable to other developers and may have framework support (eg begin end support in WCF).

不过引进的TPL的.NET4并进一步整合新.Net4.5释放它似乎.NET是从远离的IAsyncResult移动/开始结束范式,更向基于任务异步(恕我直言preferable )。

However with the introduction of the TPL an .Net4 and further integration in the new .Net4.5 release it appears .Net is moving away from the IAsyncResult / Begin End paradigms and more towards Task based asynchrony (IMHO preferable).

所以,新的方式扔到组合:

So, to throw the new way into the mix:

public Task DoSomethingAsync(string param);

和则涉及取消所有操作/访问结果可在任务对象,它允许异步机制的适当抽象,因为任何消费者只依赖于一个任务,而不是工作的发起者和手柄上被返回。

And then all operations relating to cancelling/accessing results are available on the Task object, which allows for proper abstraction of the async mechanism since any consumers only rely on a Task rather than the 'initiator' of the work AND the handle that is returned.

这篇关于使用标准的.NET异步模式的优势是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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