[英]Asynchronous Programming with Async and 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<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;
}
我的目标是.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不同。
例如,请阅读以下讨论:
我不赞成在没有.NET 4.5的机器上使用Nuget来获取.NET 4.0的扩展,因为它真正为.NET 4.5中的错误.NET 4.5或.NET 4.0带来兼容包,与.NET 4.0不兼容.NET 4.5
但是您的代码有语法错误
你应该在AccessTheWebAsync()
方法声明中返回类型Task<string[]>
,而不是你的Task<string>
,即你应该写:
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的代码在我的真正的.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中使用async,请阅读以下文章: http : //blogs.msdn.com/b/lucian/archive/2012/04/24/async-targeting-pack.aspx 。
您必须使用BCL.Async
库,如此处所述: 使用async而不使用.net 4.5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.