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;
}
4

3 回答 3

6

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

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

我不建议在没有 .NET 4.5 的机器上使用 Nuget 来获取 .NET 4.0 的扩展,因为它确实为错误的 .NET 4.5 或来自 .NET 4.5 的 .NET 4.0 带来了兼容包,与没有 .NET 4.5 的 .NET 4.0 不兼容

但是您的代码有语法错误

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

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

代替

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

为了让这个方法返回 type 的值string[]

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

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

为什么我的回答被否决了?匿名...

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

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

于 2013-04-19T05:09:12.690 回答
3

NuGet 管理器中搜索async并安装Microsoft Async以在中运行/编码asyncawait

于 2015-09-30T07:38:14.130 回答
1

您必须使用BCL.Async此处描述的库: Using async without .net 4.5

于 2013-11-07T14:52:44.567 回答