End or exit C # Async method with "return"

I was new to the async-await method in C# 5.0 and I have few questions in my head

  • What is the best way to avoid the async method if it does not pass the input argument or null check?

  • What is the logical flow of using return; in the Task async method (in some cases, it has become an infinite loop)?

  • Is CancellationToken or Task.Yield 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); } 
+7
c # asynchronous task-parallel-library async-await
source share
3 answers

The best way to "nullify any problem" IMHO is to throw an appropriate exception , but you can just use return; if you want to avoid exceptions.

This will create a completed / failed task that was executed synchronously, so the caller using await will receive the completed task and continue to use the same thread.


  • CancellationToken allows the caller to cancel the operation, which is not the way you describe.

  • Task.Yield does not complete any operation, it simply launches other tasks for some time and rebuilds itself for further use.

+7
source share

You can return from the asynchronization method at any time. In your case (the method returns the task), the compiler will generate the completed task, so any caller waiting for your function will continue.

+1
source share

When an exception is thrown from the async method, it is captured in the task, so it does not throw until the task is detected by calling Task.Wait() , Task.Result , waiting for the task or accessing the Exceptions property of the task.

In terms of input arguments, one way around this is to split the method into two parts, first check the input arguments, and then call the second method, which is equal to async . See this answer to Stephen Cleary's question for an example. Thus, the exception of the input argument will be thrown immediately outside the task returned by the method.

0
source share

All Articles