English 中文(简体)
在任务平行图书馆翻译空白任务例外
原标题:Translating exceptions for void Tasks with Task Parallel Library a la await

我需要以同样的方式翻译由<代码>Task<T>产生的例外情况,这样,通常的同步代码可以做到以下几点:

try {
  client.Call();
} catch(FaultException ex) {
    if (ex.<Some check>)
        throw new Exception("translated");
}

然而,我想以同样的方式来做,即:Call上文实际上为Task CallAsync()

因此,在C# 5中,我的方法是:

async Task CallAndTranslate()
{
    try{
        await client.CallAsync();
    } catch(FaultException ex) {
        if (ex.FaultCode ...)
            throw new Exception("translated");
    }
}

但是,现在使用C# 4。

因此,我可以做些什么,因为我想要启动一项任务,但却有(TPL)的任务。 Fault betrans, 然后再次将整件事情作为Task<T>?

  • originally emanating from a WCF webservice but that s not important here

EDIT:略微更具体地说:

public class TranslatingExceptions
{
    public Task ApiAsync() // The inner layer exposes it exactly this way
    {
        return Task.Factory.StartNew(()=>{ throw new Exception( "Argument Null" );});
    }

    public Task WrapsApiAsync() // this layer needs to expose it exactly this way
    {
        // async preview pseudocode for what I need to do                            
        try {
            await ApiAsync(  );
        } catch (Exception exception){
            if( exception.Message == "Argument Null"  )
                throw new ArgumentNullException();
        }
    }

    [Fact]
    public void Works()
    {
        var exception = Record.Exception( () => 
            WrapsApiAsync().Wait());
        Assert.IsType<ArgumentNullException>( exception.InnerException);
    }
}

如果没有需要C# 5,你将如何执行<条码>。

最佳回答

因此,现在我完全清楚一下你重新寻找的东西,在这里,各位都需要做些什么来在4年建设同等的东西:

public class TranslatingExceptions
{
    public Task ApiAsync() // The inner layer exposes it exactly this way
    {
        return Task.Factory.StartNew(()=>{ throw new Exception( "Argument Null" );});
    }

    public Task WrapsApiAsync() // this layer needs to expose it exactly this way
    {
        // Grab the task that performs the "original" work
        Task apiAsyncTask = ApiAsync();

        // Hook a continuation to that task that will do the exception "translation"
        Task result = aspiAsync.ContinueWith(antecedent =>
        {
            // Check if the antecedent faulted, if so check what the exception s message was
            if ( antecedent.IsFaulted 
              && antecedent.Exception.InnerException.Message == "Argument Null" )
            {
                throw new ArgumentNullException();
            }
        },
        TaskContinuationOptions.ExecuteSynchronously);

        // Now we return the continuation Task from the wrapper method so that the caller of the wrapper method waits on that
        return result;
    }

    [Fact]
    public void Works()
    {
        var exception = Record.Exception(() => 
                                         WrapsApiAsync().Wait());

        Assert.IsType<ArgumentNullException>(exception.InnerException);
    }
}

这应当完成你们重新寻找的东西。 值得注意的是,我使用<代码>。 TaskContinuationOptions.ExecuteSynchronously 在创造延续性时。 这是因为这项工作规模小,很紧,你不想接过头等头,而坐视仪要从地下室抽取,然后才能进行这种检查。

问题回答

暂无回答




相关问题
Manually implementing high performance algorithms in .NET

As a learning experience I recently tried implementing Quicksort with 3 way partitioning in C#. Apart from needing to add an extra range check on the left/right variables before the recursive call, ...

Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

How do I compare two decimals to 10 decimal places?

I m using decimal type (.net), and I want to see if two numbers are equal. But I only want to be accurate to 10 decimal places. For example take these three numbers. I want them all to be equal. 0....

Exception practices when creating a SynchronizationContext?

I m creating an STA version of the SynchronizationContext for use in Windows Workflow 4.0. I m wondering what to do about exceptions when Post-ing callbacks. The SynchronizationContext can be used ...

Show running instance in single instance application

I am building an application with C#. I managed to turn this into a single instance application by checking if the same process is already running. Process[] pname = Process.GetProcessesByName("...

How to combine DataTrigger and EventTrigger?

NOTE I have asked the related question (with an accepted answer): How to combine DataTrigger and Trigger? I think I need to combine an EventTrigger and a DataTrigger to achieve what I m after: when ...

热门标签