C# 为什么WCF异步方法不';当同步执行时,是否不会引发FaultException?
我已经用WCF做了一些测试,但有一点我不太清楚 我有以下服务:C# 为什么WCF异步方法不';当同步执行时,是否不会引发FaultException?,c#,wcf,asynchronous,task,C#,Wcf,Asynchronous,Task,我已经用WCF做了一些测试,但有一点我不太清楚 我有以下服务: [ServiceContract] public interface ICommunicationIssuesService:IService { [OperationContract] void TestExceptionInActionSync(); [OperationContract] Task TestExceptionInActionAsync(); } 通过以下实施: public c
[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();
}
}
在客户端,我创建了一个ChannelFactory,然后在其上:
//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
}
//同步测试
//... 工厂的设置
ICommunicationIssuseService通道=_channelFactory.CreateChannel()
试一试{
channel.testExceptionActionSync();
}捕获(错误异常){
//我收到一个例外
}
//异步测试
//... 工厂的设置
ICommunicationIssuseService通道=_channelFactory.CreateChannel()
试一试{
channel.testExceptionActionAsync();
}捕获(聚合异常){
//我收到一个AggregateException,我想是因为它是一项落后的任务
}
我不明白的是为什么我在这里没有收到FaultException(或AggregateException)?此行为是在
异步API中设计的,您需要使用任务访问返回的任务。结果或任务。等待,以获取异常,由于这是一个异步实现,因此等待任务
也可以。上述调用Wait
,Result
,Wait
有助于在任务中展开异常,因为它们试图访问异常的任务状态,该状态为Faulted
,并尝试访问结果(如果有或可能只是等待完成),即使它有异常,也请检查
按如下所示修改代码:
wait channel.testExceptionActionAsync()代码>