Share via


async (C# Reference)

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<int> ExampleMethodAsync()
{
    // . . . .
}

If you're new to asynchronous programming, you can find an introduction in Asynchronous Programming with Async and Await (C# and Visual Basic).

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 contents = await contentsTask;

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. See Compiler Warning (level 1) CS4014.

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.

Example

The following example shows the structure and flow of control between an async event handler, StartButton_Click, and an async method, ExampleMethodAsync. The result from the async method is the length of a downloaded website.

You can download this example from Developer Code Samplesand then open and run it in Visual Studio 2012. The example contains both a Windows Presentation Foundation (WPF) version and a Windows Store version of the app.

// You can use this code to create either a WPF app or a Windows Store app. 
// Either way, the code requires Visual Studio 2012.
// You need a button (StartButton) and a textbox (ResultsTextBox).

// To create this example as a Windows Store app, you must add using
// directives for System.Net.Http and System.Threading.Tasks. 
        
// To create this example as a desktop app, you must  add a reference and a 
// using directive for System.Net.Http.

private async void StartButton_Click(object sender, RoutedEventArgs e)
{
    // ExampleMethodAsync returns a Task<int> and has an int result.
    // A value is assigned to intTask when ExampleMethodAsync reaches
    // an await.
    try
    {
        Task<int> intTask = ExampleMethodAsync();
        // You can do other work here that doesn't require the result from
        // ExampleMethodAsync. . . .
        ResultsTextBox.Text += "Doing other work before awaiting intTask. . . . .\n";

        // Wait for intTask to complete, and then access the int result.
        int intResult = await intTask;

        // Or you can combine the previous two steps:
        //int intResult = await ExampleMethodAsync();

        // Process the result (intResult) . . . .
        ResultsTextBox.Text += String.Format("Length: {0}\n\n", intResult);
    }
    catch (Exception)
    {
        // Process the exception. . . .
    }
}

public async Task<int> ExampleMethodAsync()
{
    var httpClient = new HttpClient();

    // The following line activates GetStringAsync, which is an asynchronous method.
    Task<string> contentsTask = httpClient.GetStringAsync("https://msdn.microsoft.com");

    // While the task is active, you can do other work.
    ResultsTextBox.Text += "Doing other work before awaiting contentsTask. . . . .\n";

    // When you await contentsTask, execution in ExampleMethodAsync is suspended,
    // and control returns to the caller, StartButton_Click.
    string contents = await contentsTask;

    // After contentTask completes, you can calculate the length of the string.
    int exampleInt = contents.Length;

    //// You can combine the previous sequence into a single statement.
    //int exampleInt = (await httpClient.GetStringAsync("https://msdn.microsoft.com")).Length;

    ResultsTextBox.Text += "Preparing to finish ExampleMethodAsync.\n";

    // After the following return statement, any method that's awaiting
    // ExampleMethodAsync (in this case, StartButton_Click) can get the integer result.
    return exampleInt;
}
// Sample output:

// Doing other work before awaiting contentsTask. . . . .
// Doing other work before awaiting intTask. . . . .
// Preparing to finish ExampleMethodAsync.
// Length: 53292

Important

For a full WPF example that uses similar elements, see Walkthrough: Accessing the Web by Using Async and Await (C# and Visual Basic). You can download the walkthrough code from Developer Code Samples.

Return Types

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

You specify Task<TResult> 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.

For more information and examples, see Async Return Types (C# and Visual Basic).

See Also

Tasks

Walkthrough: Accessing the Web by Using Async and Await (C# and Visual Basic)

Reference

await (C# Reference)

AsyncStateMachineAttribute

Concepts

Asynchronous Programming with Async and Await (C# and Visual Basic)