使用Async和Await进行异步编程

我正在阅读本教程,了解如何在c#中异步编程并遇到错误我不知道如何解决。 这是链接: http : //msdn.microsoft.com/en-us/library/hh191443.aspx ,错误是:

Cannot find all types required by the 'async' modifier. Are you targeting the wrong framework version, or missing a reference to an assembly? 

我的目标是.NET 4.0框架,并且不确定是否需要任何其他程序集。

这是代码:

 public async Task AccessTheWebAsync(Class1 class1, Class2 class2) { // GetStringAsync returns a Task. That means that when you await the // task you'll get a List (urlContents). Task listTask = GetList(class1); // send message task // You can do work here that doesn't rely on the string from GetStringAsync. //CompareService(); // The await operator suspends AccessTheWebAsync. // - AccessTheWebAsync can't continue until getStringTask is complete. // - Meanwhile, control returns to the caller of AccessTheWebAsync. // - Control resumes here when getStringTask is complete. // - The await operator then retrieves the string result from getStringTask. string[] listContents = await listTask; // The return statement specifies an integer result. // Any methods that are awaiting AccessTheWebAsync retrieve the length value. return listContents; } public Task GetList(Class1 class1) { var taskArray = Task.Factory.StartNew(() => GenerateResults(class1)); return taskArray; } public string[] GenerateResults(Class1 class1) { string[] results = new string[2]; results[1] = ""; results[2] = ""; return results; } 

我的目标是.NET 4.0框架,并且不确定是否需要任何其他程序集

可以在.NET 4.0中运行async/await代码,而无需调用.NET 4.5, 包含或引用Async CTP中的AsyncCtpLibrary.dll 。 在Windows XP上安装.NET 4.5或Visual Studio 2012是不可能的,如果没有安装.NET 4.5,.NET 4.0与安装了.NET 4.5的.NET 4.0不同。
例如,请阅读以下讨论:

  • 在MSDN论坛上: “如果我的目标.net 4.0,但在具有.net 4.5的机器上运行,.net 4.0 WPF错误仍然存​​在?”

我不赞成在没有.NET 4.5的机器上使用Nuget来获取.NET 4.0的扩展,因为它实际上为.NET 4.5中的错误.NET 4.5或.NET 4.0带来兼容包,与.NET 4.0不兼容.NET 4.5

但是您的代码有语法错误

你应该在AccessTheWebAsync()方法声明中返回类型Task ,而不是你的Task ,即你应该写:

 public async Task AccessTheWebAsync(Class1 class1, Class2 class2)() 

代替

 public async Task AccessTheWebAsync(Class1 class1, Class2 class2)() 

为了使此方法返回string[]类型的值:

 return listContents;//where listContents is declared as string[] type 

更新:
检查OP的代码在我的真正的.NET 4.0(没有.NET 4.5和VS2012)Windows XP机器上使用Async CTP进行此更正后运行

为什么我的回答被低估? 匿名…

很明显,如果OP问这样的问题,他没有安装.NET 4.5。 他将无法在不安装VS2012的情况下使用Async Targeting Pack引用“Async for .NET Framework 4,Silverlight 4和5以及Windows Phone 7.5和8 1.0.16”,而后者在Wondows XP上完全不可能与Nuget一起使用在没有安装.NET 4.5的.NET 4.0上,VS2010中的错误包装不兼容且无法使用

在可能的情况下,检查了很多次

NuGet管理器中搜索异步并安装Microsoft Async以在.net4中运行async / await代码

要使用与.NET 4.0的异步,请阅读以下文章: http : //blogs.msdn.com/b/lucian/archive/2012/04/24/async-targeting-pack.aspx 。

您必须使用BCL.Async库,如此处所述: 使用async而不使用.net 4.5