Task asynchronous programming model

You lot tin avoid operation bottlenecks and heighten the overall responsiveness of your application past using asynchronous programming. Yet, traditional techniques for writing asynchronous applications can be complicated, making them difficult to write, debug, and maintain.

C# 5 introduced a simplified approach, async programming, that leverages asynchronous support in the .NET Framework 4.5 and higher, .Net Core, and the Windows Runtime. The compiler does the difficult work that the developer used to do, and your awarding retains a logical structure that resembles synchronous code. As a consequence, you go all the advantages of asynchronous programming with a fraction of the effort.

This topic provides an overview of when and how to apply async programming and includes links to support topics that contain details and examples.

Async improves responsiveness

Asynchrony is essential for activities that are potentially blocking, such as web access. Access to a web resource sometimes is deadening or delayed. If such an activity is blocked in a synchronous process, the entire application must wait. In an asynchronous process, the awarding can go on with other work that doesn't depend on the spider web resources until the potentially blocking job finishes.

The post-obit table shows typical areas where asynchronous programming improves responsiveness. The listed APIs from .Net and the Windows Runtime comprise methods that support async programming.

Application expanse .NET types with async methods Windows Runtime types with async methods
Spider web access HttpClient Windows.Spider web.Http.HttpClient
SyndicationClient
Working with files JsonSerializer
StreamReader
StreamWriter
XmlReader
XmlWriter
StorageFile
Working with images MediaCapture
BitmapEncoder
BitmapDecoder
WCF programming Synchronous and Asynchronous Operations

Asynchrony proves particularly valuable for applications that admission the UI thread because all UI-related activity usually shares ane thread. If any process is blocked in a synchronous application, all are blocked. Your awarding stops responding, and you might conclude that information technology has failed when instead it's simply waiting.

When you apply asynchronous methods, the application continues to respond to the UI. You can resize or minimize a window, for example, or yous can close the application if you don't want to look for it to stop.

The async-based arroyo adds the equivalent of an automatic transmission to the list of options that you can cull from when designing asynchronous operations. That is, yous get all the benefits of traditional asynchronous programming but with much less effort from the developer.

Async methods are easy to write

The async and await keywords in C# are the eye of async programming. Past using those two keywords, you tin use resources in .Internet Framework, .Cyberspace Cadre, or the Windows Runtime to create an asynchronous method almost as easily as you create a synchronous method. Asynchronous methods that you lot ascertain by using the async keyword are referred to every bit async methods.

The following example shows an async method. Almost everything in the code should await familiar to you.

You tin observe a complete Windows Presentation Foundation (WPF) example available for download from Asynchronous programming with async and look in C#.

              public async Task<int> GetUrlContentLengthAsync() {     var customer = new HttpClient();      Task<string> getStringTask =         client.GetStringAsync("https://docs.microsoft.com/dotnet");      DoIndependentWork();      string contents = wait getStringTask;      return contents.Length; }  void DoIndependentWork() {     Console.WriteLine("Working..."); }                          

You lot tin larn several practices from the preceding sample. Showtime with the method signature. It includes the async modifier. The return blazon is Chore<int> (Come across "Return Types" section for more options). The method name ends in Async. In the trunk of the method, GetStringAsync returns a Job<cord>. That means that when y'all wait the task you'll get a string (contents). Before pending the chore, you lot tin can do piece of work that doesn't rely on the string from GetStringAsync.

Pay shut attending to the await operator. It suspends GetUrlContentLengthAsync:

  • GetUrlContentLengthAsync can't continue until getStringTask is consummate.
  • Meanwhile, control returns to the caller of GetUrlContentLengthAsync.
  • Control resumes here when getStringTask is complete.
  • The await operator and then retrieves the cord result from getStringTask.

The render statement specifies an integer outcome. Any methods that are awaiting GetUrlContentLengthAsync retrieve the length value.

If GetUrlContentLengthAsync doesn't accept whatsoever work that it tin can do between calling GetStringAsync and awaiting its completion, you can simplify your code by calling and awaiting in the following unmarried statement.

              string contents = expect customer.GetStringAsync("https://docs.microsoft.com/dotnet");                          

The following characteristics summarize what makes the previous case an async method:

  • The method signature includes an async modifier.

  • The name of an async method, by convention, ends with an "Async" suffix.

  • The return type is one of the post-obit types:

    • Task<TResult> if your method has a return argument in which the operand has type TResult.
    • Task if your method has no return statement or has a return statement with no operand.
    • void if you're writing an async result handler.
    • Any other type that has a GetAwaiter method (starting with C# 7.0).

    For more data, run into the Return types and parameters section.

  • The method commonly includes at least one expect expression, which marks a point where the method tin't proceed until the awaited asynchronous operation is complete. In the meantime, the method is suspended, and command returns to the method's caller. The next department of this topic illustrates what happens at the suspension point.

In async methods, yous employ the provided keywords and types to point what you desire to do, and the compiler does the rest, including keeping track of what must happen when control returns to an await bespeak in a suspended method. Some routine processes, such equally loops and exception treatment, can be difficult to handle in traditional asynchronous lawmaking. In an async method, you write these elements much as you would in a synchronous solution, and the trouble is solved.

For more than information about asynchrony in previous versions of .NET Framework, see TPL and traditional .NET Framework asynchronous programming.

What happens in an async method

The near important thing to empathize in asynchronous programming is how the command flow moves from method to method. The following diagram leads you through the process:

Trace navigation of async control flow

The numbers in the diagram stand for to the following steps, initiated when a calling method calls the async method.

  1. A calling method calls and awaits the GetUrlContentLengthAsync async method.

  2. GetUrlContentLengthAsync creates an HttpClient instance and calls the GetStringAsync asynchronous method to download the contents of a website as a string.

  3. Something happens in GetStringAsync that suspends its progress. Maybe information technology must expect for a website to download or another blocking activity. To avoid blocking resources, GetStringAsync yields control to its caller, GetUrlContentLengthAsync.

    GetStringAsync returns a Task<TResult>, where TResult is a string, and GetUrlContentLengthAsync assigns the chore to the getStringTask variable. The task represents the ongoing process for the call to GetStringAsync, with a delivery to produce an actual string value when the work is consummate.

  4. Because getStringTask hasn't been awaited still, GetUrlContentLengthAsync can continue with other work that doesn't depend on the final consequence from GetStringAsync. That work is represented by a call to the synchronous method DoIndependentWork.

  5. DoIndependentWork is a synchronous method that does its piece of work and returns to its caller.

  6. GetUrlContentLengthAsync has run out of work that it can do without a result from getStringTask. GetUrlContentLengthAsync side by side wants to calculate and return the length of the downloaded string, but the method can't calculate that value until the method has the string.

    Therefore, GetUrlContentLengthAsync uses an await operator to suspend its progress and to yield control to the method that chosen GetUrlContentLengthAsync. GetUrlContentLengthAsync returns a Job<int> to the caller. The chore represents a promise to produce an integer consequence that's the length of the downloaded string.

    Note

    If GetStringAsync (and therefore getStringTask) completes before GetUrlContentLengthAsync awaits information technology, control remains in GetUrlContentLengthAsync. The expense of suspending and so returning to GetUrlContentLengthAsync would be wasted if the called asynchronous process getStringTask has already completed and GetUrlContentLengthAsync doesn't have to wait for the final result.

    Inside the calling method the processing blueprint continues. The caller might do other piece of work that doesn't depend on the event from GetUrlContentLengthAsync earlier awaiting that consequence, or the caller might await immediately. The calling method is waiting for GetUrlContentLengthAsync, and GetUrlContentLengthAsync is waiting for GetStringAsync.

  7. GetStringAsync completes and produces a string result. The string issue isn't returned past the phone call to GetStringAsync in the way that you lot might wait. (Remember that the method already returned a task in step 3.) Instead, the cord outcome is stored in the task that represents the completion of the method, getStringTask. The look operator retrieves the issue from getStringTask. The consignment statement assigns the retrieved result to contents.

  8. When GetUrlContentLengthAsync has the cord result, the method can calculate the length of the cord. So the work of GetUrlContentLengthAsync is likewise consummate, and the waiting effect handler can resume. In the full example at the end of the topic, you can confirm that the event handler retrieves and prints the value of the length result. If you are new to asynchronous programming, have a minute to consider the difference between synchronous and asynchronous behavior. A synchronous method returns when its work is complete (step five), merely an async method returns a task value when its piece of work is suspended (steps 3 and half-dozen). When the async method eventually completes its work, the task is marked as completed and the result, if any, is stored in the chore.

API async methods

Y'all might be wondering where to find methods such every bit GetStringAsync that back up async programming. .NET Framework 4.5 or higher and .NET Core contain many members that work with async and await. You can recognize them by the "Async" suffix that's appended to the fellow member name, and by their render type of Job or Task<TResult>. For example, the System.IO.Stream grade contains methods such every bit CopyToAsync, ReadAsync, and WriteAsync alongside the synchronous methods CopyTo, Read, and Write.

The Windows Runtime also contains many methods that you tin can use with async and await in Windows apps. For more information, see Threading and async programming for UWP development, and Asynchronous programming (Windows Store apps) and Quickstart: Calling asynchronous APIs in C# or Visual Basic if you utilize earlier versions of the Windows Runtime.

Threads

Async methods are intended to be non-blocking operations. An look expression in an async method doesn't cake the electric current thread while the awaited chore is running. Instead, the expression signs upwardly the rest of the method every bit a continuation and returns command to the caller of the async method.

The async and wait keywords don't crusade additional threads to exist created. Async methods don't require multithreading because an async method doesn't run on its own thread. The method runs on the current synchronization context and uses time on the thread only when the method is active. Y'all can utilize Task.Run to motion CPU-jump work to a background thread, simply a groundwork thread doesn't help with a procedure that's merely waiting for results to go bachelor.

The async-based approach to asynchronous programming is preferable to existing approaches in almost every case. In particular, this approach is better than the BackgroundWorker class for I/O-bound operations because the lawmaking is simpler and you don't have to baby-sit against race conditions. In combination with the Chore.Run method, async programming is better than BackgroundWorker for CPU-bound operations because async programming separates the coordination details of running your lawmaking from the work that Task.Run transfers to the thread pool.

async and wait

If you specify that a method is an async method by using the async modifier, you enable the post-obit 2 capabilities.

  • The marked async method tin apply await to designate suspension points. The look operator tells the compiler that the async method can't continue by that point until the awaited asynchronous process is complete. In the concurrently, command returns to the caller of the async method.

    The suspension of an async method at an expect expression doesn't institute an go out from the method, and finally blocks don't run.

  • The marked async method tin can itself be awaited by methods that call information technology.

An async method typically contains one or more occurrences of an wait operator, but the absence of await expressions doesn't crusade a compiler fault. If an async method doesn't use an wait operator to marker a suspension bespeak, the method executes as a synchronous method does, despite the async modifier. The compiler bug a warning for such methods.

async and wait are contextual keywords. For more data and examples, encounter the following topics:

  • async
  • await

Return types and parameters

An async method typically returns a Chore or a Task<TResult>. Within an async method, an expect operator is practical to a task that'due south returned from a phone call to another async method.

You specify Job<TResult> as the render type if the method contains a render statement that specifies an operand of blazon TResult.

Yous utilize Task as the return type if the method has no return statement or has a return statement that doesn't return an operand.

Starting with C# vii.0, you can besides specify whatever other return blazon, provided that the type includes a GetAwaiter method. ValueTask<TResult> is an instance of such a blazon. It is bachelor in the System.Threading.Tasks.Extension NuGet package.

The following example shows how you declare and telephone call a method that returns a Task<TResult> or a Task:

              async Task<int> GetTaskOfTResultAsync() {     int hours = 0;     await Job.Delay(0);      render hours; }   Task<int> returnedTaskTResult = GetTaskOfTResultAsync(); int intResult = await returnedTaskTResult; // Single line // int intResult = await GetTaskOfTResultAsync();  async Chore GetTaskAsync() {     expect Task.Delay(0);     // No return argument needed }  Job returnedTask = GetTaskAsync(); await returnedTask; // Single line await GetTaskAsync();                          

Each returned task represents ongoing work. A task encapsulates information nearly the state of the asynchronous process and, eventually, either the concluding result from the process or the exception that the process raises if it doesn't succeed.

An async method can also have a void return blazon. This return type is used primarily to define event handlers, where a void return type is required. Async result handlers oftentimes serve as the starting point for async programs.

An async method that has a void return type can't be awaited, and the caller of a void-returning method can't grab any exceptions that the method throws.

An async method can't declare in, ref or out parameters, merely the method tin call methods that accept such parameters. Similarly, an async method tin can't render a value by reference, although it tin can call methods with ref return values.

For more information and examples, meet Async return types (C#). For more than information about how to take hold of exceptions in async methods, encounter endeavor-take hold of.

Asynchronous APIs in Windows Runtime programming have one of the following return types, which are similar to tasks:

  • IAsyncOperation<TResult>, which corresponds to Task<TResult>
  • IAsyncAction, which corresponds to Task
  • IAsyncActionWithProgress<TProgress>
  • IAsyncOperationWithProgress<TResult,TProgress>

Naming convention

By convention, methods that return commonly awaitable types (for example, Task, Job<T>, ValueTask, ValueTask<T>) should take names that end with "Async". Methods that start an asynchronous operation but do non return an awaitable type should not have names that end with "Async", simply may start with "Begin", "Start", or some other verb to suggest this method does not return or throw the result of the performance.

You can ignore the convention where an event, base of operations grade, or interface contract suggests a different proper noun. For example, you shouldn't rename mutual event handlers, such every bit OnButtonClick.

Title Description
How to make multiple web requests in parallel by using async and await (C#) Demonstrates how to start several tasks at the same fourth dimension.
Async return types (C#) Illustrates the types that async methods can return, and explains when each type is appropriate.
Abolish tasks with a cancellation token as a signaling mechanism. Shows how to add the post-obit functionality to your async solution:

- Cancel a list of tasks (C#)
- Cancel tasks afterward a flow of time (C#)
- Process asynchronous task as they complete (C#)

Using async for file admission (C#) Lists and demonstrates the benefits of using async and await to access files.
Task-based asynchronous blueprint (TAP) Describes an asynchronous pattern, the blueprint is based on the Task and Task<TResult> types.
Async Videos on Aqueduct nine Provides links to a multifariousness of videos about async programming.

See too

  • Asynchronous programming with async and await
  • async
  • await