Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
188 views
in Technique[技术] by (71.8m points)

c# - 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?

question from:https://stackoverflow.com/questions/9574790/creating-an-async-method-in-net-4-0-that-can-be-used-with-await-in-net-4-5

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...