我写了一些WCF服务,我想以最有效的方式编写它们。这意味着服务器端和客户端都将公开异步操作。
客户端
我知道在客户端合同中,我可以通过添加" Assync"来公开异步操作。后缀:
[ServiceContract]
public interface IService1
{
[OperationContract]
string GetData(int value);
[OperationContract]
Task<string> GetDataAsync(int value);
}
服务器端
服务器端对我来说并不那么明显。在服务器端,我想只保留异步操作:
[ServiceContract]
public interface IService1
{
[OperationContract]
Task<string> GetDataAsync(int value);
}
根据How to: Implement an Asynchronous Service Operation,我应该使用IAssyncResult:
[OperationContractAttribute(AsyncPattern=true)]
IAsyncResult BeginServiceAsyncMethod(string msg, AsyncCallback callback, object asyncState);
然而,这似乎很乏味。
为什么使用IAssyncResult而不是基于任务的异步操作的目的是什么?在WCF中实现异步服务器端的正确方法是什么?
答案 0 :(得分:4)
如果你看一下documentation(强调我的):
异步编程模型(APM)模式(也称为
IAsyncResult
模式),其中异步操作需要Begin和End方法(例如,BeginWrite
和EndWrite
用于异步写入操作) 。 此模式不再推荐用于新开发。有关详细信息,请参阅Asynchronous Programming Model (APM)。
与
基于任务的异步模式(TAP),它使用单个方法来表示异步操作的启动和完成。 TAP是在.NET Framework 4中引入的,是.NET Framework中异步编程的推荐方法。 C#中的
async
和await
关键字以及Visual Basic语言中的Async
和Await
运算符为TAP添加了语言支持。有关详细信息,请参阅Task-based Asynchronous Pattern (TAP)。
所以:
您正在阅读的文章来自.NET 4.0之前的版本(因此它已经很老了)。使用Task
并忘记IAsyncResult
存在。