Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an async method in .NET 4.0 that can be used with "await" in .NET 4.5

I have a .NET project that uses C# in .NET 4.0 and VS2010.

What I would like to do is add some async overloads to my library to make doing async programming easier for users in .NET 4.5 with the await keyword. Right now the methods that are being overloaded are non-asynchronous. Also I don't want to use any async methods myself, just create new ones and make them available.

Is creating async methods in .NET 4.0 and VS2010 possible and if so, what should the .NET 4.0 async method look like?

Because I'm using VS2010 I don't have access to the "async" keyword so what needs to happen to emulate that behavior in .NET 4.0? For example does it need to return any particular type, and does any code need to happen inside the method to make the currently non-asynchronous code it is calling happen asynchronously?

like image 568
James Newton-King Avatar asked Mar 05 '12 22:03

James Newton-King


People also ask

How can create async method in C#?

You can use await Task. Yield(); in an asynchronous method to force the method to complete asynchronously. Insert it at beginning of your method and it will then return immediately to the caller and complete the rest of the method on another thread.

Do you have to await an async function C#?

async methods need to have an await keyword in their body or they will never yield! This is important to keep in mind. If await is not used in the body of an async method, the C# compiler generates a warning, but the code compiles and runs as if it were a normal method.

How use async await in asp net?

You can use the await keyword only in methods annotated with the async keyword. The await keyword does not block the thread until the task is complete. It signs up the rest of the method as a callback on the task, and immediately returns.

Why would you use asynchronous actions?

Asynchronous actions are best when your method is I/O, network-bound, or long-running and parallelizable. Another benefit of an asynchronous action is that it can be more easily canceled by the user than a synchronous request.


1 Answers

As others have stated, you start by having a method return Task or Task<TResult>. This is sufficient to await its result in .NET 4.5.

To have your method fit in as well as possible with future asynchronous code, follow the guidelines in the Task-based Asynchronous Pattern document (also available on MSDN). It provides naming conventions and parameter recommendations, e.g., for supporting cancellation.

For the implementation of your method, you have a few choices:

  • If you have existing IAsyncResult-based asynchronous methods, use Task.Factory.FromAsync.
  • If you have another asynchronous system, use TaskCompletionSource<TResult>.
like image 69
Stephen Cleary Avatar answered Oct 14 '22 19:10

Stephen Cleary