在 .NET 4.0 中创建可与“await"一起使用的异步方法在 .NET 4.5 中 [英] Creating an async method in .NET 4.0 that can be used with "await" in .NET 4.5

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

问题描述

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

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

我想做的是向我的库中添加一些异步重载,以便使用 await 关键字使 .NET 4.5 中的用户更容易进行异步编程.现在正在重载的方法是非异步的.此外,我不想自己使用任何异步方法,只需创建新方法并使其可用.

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,所以我无法访问async"关键字,那么在 .NET 4.0 中模拟该行为需要做什么?例如,它是否需要返回任何特定类型,以及是否需要在方法内部发生任何代码以使其正在调用的当前非异步代码异步发生?

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?

推荐答案

正如其他人所说,您首先让方法返回 TaskTask.这足以在 .NET 4.5 中await它的结果.

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.

为了让您的方法尽可能适合未来的异步代码,请遵循 基于任务的异步模式文档(也可在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 中创建可与“await"一起使用的异步方法在 .NET 4.5 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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