【问题标题】:Why WCF async method doesn't throw a FaultException when a sync do?为什么 WCF 异步方法在同步时不会抛出 FaultException?
【发布时间】:2018-02-02 13:00:48
【问题描述】:

我用 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();
    }
}

在客户端,我创建了一个 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)?

【问题讨论】:

    标签: c# wcf asynchronous task


    【解决方案1】:

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

    修改你的代码如下:

    await channel.TestExceptionInActionAsync();

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-17
      • 2018-12-29
      • 2011-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多