使用Async和Await进行异步编程

10
我正在学习如何在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<string> AccessTheWebAsync(Class1 class1, Class2 class2)
{
  // GetStringAsync returns a Task<string>. That means that when you await the 
  // task you'll get a List<string> (urlContents).
  Task<string[]> 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<string[]> GetList(Class1 class1)
{
    var taskArray = Task<string[]>.Factory.StartNew(() => GenerateResults(class1));
    return taskArray;
}
public string[] GenerateResults(Class1 class1)
{
    string[] results = new string[2];
    results[1] = "";
    results[2] = "";
    return results;
}

2
异步 - 等待是来自 .NET Framework 4.5,而不是 4。 - cuongle
2
@CuongLe,“async/await”来自“C#-5.0”,但我在安装了“Async CTP”的.NET 4.0中使用它,因为我无法在Windows XP(VS2010)上安装.NET-4.5(或VS2012)。将其视为真正.NET-4.0的扩展,而不是仅适用于.NET-4.5的扩展。 - Gennady Vanin Геннадий Ванин
3个回答

6

我正在针对.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论坛上:{{link2:“如果我针对.NET 4.0但在拥有.NET 4.5的计算机上运行,.NET 4.0 WPF错误仍会存在吗?”}}
我建议不要在没有安装.NET 4.5的计算机上使用Nuget获取.NET 4.0的扩展,因为它会带来不兼容的包,可能是针对错误的.NET 4.5或.NET 4.0从.NET 4.5不兼容的版本而来,没有.NET 4.5。
但是你的代码有语法错误。
在AccessTheWebAsync()方法声明中,你应该有返回类型Task,而不是你的Task,即你应该写:
public async Task<string[]> AccessTheWebAsync(Class1 class1, Class2 class2)()  

替代

public async Task<string> AccessTheWebAsync(Class1 class1, Class2 class2)()

为了使该方法返回 string[] 类型的值:
return listContents;//where listContents is declared as string[] type   

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

为什么我的答案被匿名地下降了...

很明显,如果OP提出这样的问题,他没有安装.NET 4.5。他将无法使用Async Targeting Pack,引用“针对.NET Framework 4、Silverlight 4和5以及Windows Phone 7.5和8的异步1.0.16”而不安装VS2012,后者在Wondows XP上根本不可能,Nuget会在VS2010中带来不兼容并且无法在未安装.NET 4.5的情况下使用的错误包

已检查多次,在许多情境下


3
NuGet管理器中搜索async并安装Microsoft Async,以在中运行async/await代码。


1

安装包 Microsoft.Bcl.Async –pre - Marek Bar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接