建立在.NET 4.0中的异步方法可以与&QUOT使用;伺机"在.NET 4.5 [英] Creating an async method in .NET 4.0 that can be used with "await" in .NET 4.5

查看:198
本文介绍了建立在.NET 4.0中的异步方法可以与&QUOT使用;伺机"在.NET 4.5的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用C#在.NET 4.0中和VS2010的.NET项目。

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

我希望做的是添加一些异步重载到我的图书馆,使做异步编程方便了用户在.NET 4.5的的await关键字。现在正在重载的方法都是非同步的。此外,我不希望使用任何异步方法我自己,只要创建新的,让它们可用。

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.

时创造了.NET 4.0和VS2010可能的,如果是这样异步方法,应该在.NET 4.0异步方法是什么样子?

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

由于我使用VS2010我没有的异步关键字,所以访问需要做些什么来模拟在.NET 4.0中的行为吗?例如它需要返回任何特定类型,并执行任何code需要在方法内发生,使目前非异步code是异步调用发生?

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?

推荐答案

正如其他人所指出的,您有一个方法返回启动任务任务< TResult> 。这足以等待其结果在.NET 4.5。

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.

要拥有你的方法适合以及可能的未来异步code,遵循准则中的基于任务的异步模式文件(也MSDN上使用 ) 。它提供了命名约定和参数的建议,例如,支持取消。

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>.

这篇关于建立在.NET 4.0中的异步方法可以与&QUOT使用;伺机&QUOT;在.NET 4.5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆