async Modifier Keyword in C#

The async modifier indicates that the method, lambda expression, or anonymous method that it modifies is asynchronous. Such methods are referred to as async methods.

public async Task DoSomethingAsync()
    // . . . .

If you’re new to asynchronous programming, you can find an introduction of Asynchronous Programming in .NET using C# here.

An async method provides a convenient way to do potentially long-running work without blocking the caller’s thread. The caller of an async method can resume its work without waiting for the async method to finish.

Typically, a method modified by the async keyword contains at least one await expression or statement.

string Content = await getContentTask;

The method runs synchronously until it reaches its first await expression, at which point the method is suspended until the awaited task is complete. In the meantime, control returns to the caller of the method, as the example later in this topic shows.

If a method that’s modified by an async keyword doesn’t contain an await expression or statement, the method executes synchronously. A compiler warning alerts you to any async methods that don’t contain await because that situation might indicate an error.

When async modifies a method, a lambda expression, or an anonymous method, async is a keyword. In all other contexts, async is interpreted as an identifier. This distinction makes async a contextual keyword.

private async void DownloadFileButton_Click(object sender, EventArgs e)
  // Since we asynchronously wait, the UI thread is not blocked by the file download.
  await DownloadFileAsync(fileNameTextBox.Text);

  // Since we resume on the UI context, we can directly access UI elements.
  resultTextBox.Text = "File downloaded!";

Return Types

An async method can have a return type of Task or void. The method cannot declare any ref or out parameters, although it can call methods that have such parameters.

You specify Task as the return type of an async method if the return statement of the method specifies an operand of type TResult. You use Task if no meaningful value is returned when the method is completed. That is, a call to the method returns a Task, but when the Task is completed, any await expression that’s awaiting the Task evaluates to void.

The void return type is used primarily to define event handlers, where a void return type is required. The caller of a void-returning async method can’t await it and can’t catch exceptions that the method throws.

Leave a Reply

Your email address will not be published. Required fields are marked *