【发布时间】:2017-05-07 09:16:33
【问题描述】:
WCF 合同可能如下所示:
[ServiceContract]
public interface IService
{
[OperationContract]
void DoSomethingFast();
[OperationContract]
void DoSomethingSlow();
[OperationContract]
int GetSomethingFast();
[OperationContract]
int GetSomethingSlow();
}
当客户端进行任何这些调用时,它的线程会阻塞,而服务器会执行它的操作。对于Fast 方法,这没问题,但对于Slow 方法,这种阻塞远非理想。我们可以将(IsOneWay = true) 添加到DoSomething 方法中,但我们不能对GetSomething 方法做同样的事情,因为它们确实是两种方式——我们必须等待结果:
[ServiceContract]
public interface IService
{
[OperationContract(IsOneWay = true)]
void DoSomethingFast();
[OperationContract(IsOneWay = true)]
void DoSomethingSlow();
[OperationContract]
int GetSomething();
[OperationContract]
int GetSomethingSlow();
}
输入基于任务的异步模式 (TAP)。我们将合约定义为返回Task,而WCF(据我所知)在幕后做了一些魔术,并立即返回一个Task,它在完成之前等待来自WCF 服务的回调。这消除了客户端阻塞,允许使用 await 代替:
[ServiceContract]
public interface IService
{
[OperationContract(IsOneWay = true)]
Task DoSomethingFastAsync();
[OperationContract(IsOneWay = true)]
Task DoSomethingSlowAsync();
[OperationContract]
Task<int> GetSomethingAsync();
[OperationContract]
Task<int> GetSomethingSlowAsync();
}
我的问题是这一切是如何运作的,以及您是否仍需要在服务合同中包含(IsOneWay = true):
-
据我所知是否准确? WCF 是否会自动返回
Task,当服务告诉我们它已完成时,该Task已完成? - 是
(IsOneWay = true)是上述魔法发生所必需的吗?如果没有,是否有任何影响? - 鉴于来自服务的回调可以是“我完成了”或“这是你的结果”同样容易,
DoSomething和GetSomething调用是否可以同等对待?那么如果(IsOneWay = true)是必要的,是否也可以用在GetSomething方法上?
【问题讨论】:
标签: c# wcf async-await