I was new to the async-await
method in C# 5.0
, and I have few questions in my mind
What is the best way to escape an async
method if it failed an input argument or null check?
What is the logical flow of using return;
in an Task async
method (In some circumstances, it became an infinite loop)?
Is CancellationToken
or Task.Yield
fit better in this scenario?
public Func<AzureBlobInfo, string, Task> UploadSuccessCallBackAsync { get; set; }
private async Task OnUploadSuccessAsync(AzureBlobInfo info)
{
if (this.UploadSuccessCallBackAsync == null)
{
return;
}
var transactionType = this.FormData.Get("transactionType");
if (string.IsNullOrEmpty(transactionType))
{
transactionType = "unknown";
}
await this.UploadSuccessCallBackAsync(info, transactionType);
}
The best way to "fail upon some problem" IMHO would be to throw the appropriate exception, but you can definitely just use return;
if you prefer to avoid exceptions.
This will create a completed/faulted task that was completed synchronously, so the caller using await
will get a finished task and continue on using the same thread.
CancellationToken
allows for the caller to cancel the operation, which isn't the case you are describing.
Task.Yield
doesn't terminate any operation, it just enables other tasks to run for some time and reschedules itself for later.