等待任务并静默停止取消或失败

Key*_*mer -2 .net c# task

我想写的是以下内容:

async void Foo()
{
    var result = await GetMyTask().IgnoreCancelAndFailure();
    ProcessResult(result);
}
Run Code Online (Sandbox Code Playgroud)

代替:

void Foo()
{
    GetMyTask().ContinueWith(task => ProcessResult(task.Result),
        TaskContinuationOptions.OnlyOnRanToCompletion);
}
Run Code Online (Sandbox Code Playgroud)

但是我不知道如何实现IgnoreCancelAndFailure方法,它具有以下签名:

//On cancel or failure this task should simply stop and never complete.
Task<T> IgnoreCancelAndFailure<T>(this Task<T> task) 
{
     throw new NotImplementedException(); 
}
Run Code Online (Sandbox Code Playgroud)

如果可能,我应该如何实现IgnoreCancelAndFailure?

Tho*_*que 5

您可以执行类似的操作,但是您需要知道在失败的情况下您希望方法返回什么,因为需要返回值:

public static async Task<T> IgnoreCancelAndFailure<T>(this Task<T> task) 
{
     try
     {
         return await task;
     }
     catch
     {
         return ???; // whatever you want to return in this case
     }
}
Run Code Online (Sandbox Code Playgroud)

如果它是Task没有结果的,只需catch留空(或者可能记录异常...吞下异常使硬调试)

如果您只想ProcessResultGetMyTask成功时执行,则可以执行以下操作:

async void Foo()
{
    try
    {
        var result = await GetMyTask();
        ProcessResult(result);
    }
    catch(Exception ex)
    {
        // handle the exception somehow, or ignore it (not recommended)
    }
}
Run Code Online (Sandbox Code Playgroud)