为什么 WCF 异步方法在同步时不会引发错误异常?



我已经用WCF做了一些测试,但我不确定是否理解一件事。

我有以下服务:

[ServiceContract]
public interface ICommunicationIssuesService:IService
{
[OperationContract]
void TestExceptionInActionSync();
[OperationContract]
Task TestExceptionInActionAsync();
}

具有以下实现:

public class CommunicationIssuesService :  ICommunicationIssuesService
{
public void TestExceptionInActionSync()
{
throw new InvalidOperationException();
}
public async Task TestExceptionInActionAsync()
{
throw new InvalidOperationException();
}
}

在客户端,我创建了一个通道工厂,然后在它上面:

//Test Synchronous
//... Setup of the channelFactory
ICommunicationIssuesService channel =_channelFactory.CreateChannel()
try{
channel.TestExceptionInActionSync();
}catch(FaultException<ExceptionDetail>){
//I receive an FaultException
}
//Test Asynchronous
//... Setup of the channelFactory
ICommunicationIssuesService channel =_channelFactory.CreateChannel()
try{
channel.TestExceptionInActionAsync();
}catch(AggregateException){
//I receive an AggregateException, I guess because it's a Task behind   
}

我不明白的是为什么我在这里没有收到错误异常(或聚合异常(?

此行为是Async APIs中设计的,您需要使用Task.ResultTask.Wait访问返回的任务才能获得异常,因为这是一个异步实现,因此await Task也可以。上面提到的调用WaitResultawait有助于解开任务中的异常,因为它们尝试访问任务状态,该状态Faulted异常并尝试访问结果,如果有或可能只是等待完成,即使它有异常,请检查任务状态

修改代码,如下所示:

await channel.TestExceptionInActionAsync();

相关内容

最新更新