Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Terminate 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 mind

  1. What is the best way to escape an async method if it failed an input argument or null check?

  2. What is the logical flow of using return; in an Task async method (In some circumstances, it became an infinite loop)?

  3. 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);
}
like image 444
alextcl Avatar asked Jul 31 '14 09:07

alextcl


People also ask

Should you use exit in C?

Yes, it is ok to use exit in C.

What is exit () in C language?

The exit () function is used to break out of a loop. This function causes an immediate termination of the entire program done by the operation system. The general form of the exit() function is as follows − void exit (int code);

Is there exit keyword in C?

C library function - exit()The C library function void exit(int status) terminates the calling process immediately. Any open file descriptors belonging to the process are closed and any children of the process are inherited by process 1, init, and the process parent is sent a SIGCHLD signal.

Should I use exit or return in C?

For the most part, there is no difference in a C program between using return and calling exit() to terminate main() .


1 Answers

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.

like image 169
i3arnon Avatar answered Sep 27 '22 18:09

i3arnon