2017-08-24 77 views
0

我用WCF做了一些测试,我不确定要理解一件事。为什么WCF异步方法在同步时不会抛出FaultException?

我以下服务:

[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 
} 

我不明白的是为什么我在这里没有收到FaultException(或AggregateException)?

回答

0

此行为是设计在Async APIs,您需要使用Task.ResultTask.Wait,得到异常访问返回的任务,因为这是一个异步执行,因此await Task也会做。上述WaitResult提到的电话,await有助于展开在任务例外,因为他们试图进入任务状态,这是Faulted为异常,并尝试访问的结果,如果有或可能只是等待完成,甚至如果有异常,检查Task Status

修改你的代码如下:

await channel.TestExceptionInActionAsync();