我想写的是以下内容:
async void Foo() { var result = await GetMyTask().IgnoreCancelAndFailure(); ProcessResult(result); }
代替:
void Foo() { GetMyTask().ContinueWith(task => ProcessResult(task.Result), TaskContinuationOptions.OnlyOnRanToCompletion); }
但是我不知道如何实现IgnoreCancelAndFailure方法,它具有以下签名:
//On cancel or failure this task should simply stop and never complete. TaskIgnoreCancelAndFailure (this Task task) { throw new NotImplementedException(); }
如果可能,我应该如何实现IgnoreCancelAndFailure?
您可以执行类似的操作,但是您需要知道在失败的情况下您希望方法返回什么,因为需要返回值:
public static async TaskIgnoreCancelAndFailure (this Task task) { try { return await task; } catch { return ???; // whatever you want to return in this case } }
如果它是Task
没有结果的,只需catch
留空(或者可能记录异常...吞下异常使硬调试)
如果您只想ProcessResult
在GetMyTask
成功时执行,则可以执行以下操作:
async void Foo() { try { var result = await GetMyTask(); ProcessResult(result); } catch(Exception ex) { // handle the exception somehow, or ignore it (not recommended) } }