2017-08-24 78 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();