C# 等待/异步引用错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15575253/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Await/async reference error
提问by csharp newbie
im trying to do some async operation in some function returning string.
我试图在一些返回字符串的函数中做一些异步操作。
async private void button1_Click(object sender, EventArgs e)
{
string output = await thr_calc(this, null);
}
async private Task<string> thr_calc(object sender, EventArgs e)
{
return await zzztest();
}
string zzztest()
{
string asd;
//some stuff here
return asd;
}
But it gives me errors on each string contains words async/await! Im using russian version of ms vs express 2012 for windows desktop, so here is the translation of errors:
但是它给我的每个字符串都包含错误,包含单词 async/await!我在 Windows 桌面上使用俄语版的 ms vs express 2012,所以这里是错误的翻译:
Cannot find all types required by the 'async' modifier. Are you targeting the wrong framework version, or missing a reference to an assembly?
找不到“async”修饰符所需的所有类型。您的目标是错误的框架版本,还是缺少对程序集的引用?
And 2 errors:
和 2 个错误:
Predefined type 'System.Runtime.CompilerServices.IAsyncStateMachine' is not defined or imported
未定义或导入预定义类型“System.Runtime.CompilerServices.IAsyncStateMachine”
I cant find that reference. I've tried to use async/await before and it worked fine, now im doing all the same and its not. What I am missing?
我找不到那个参考。我之前尝试过使用 async/await 并且它工作得很好,现在我做的都是一样的,但不是。我缺少什么?
采纳答案by redtuna
In thr_calc, use:
return zzztest()
Also, make sure you've set your project to use .Net 4.5 or later (that's when "async" was introduced)
在 thr_calc 中,使用:
return zzztest()
此外,请确保您已将项目设置为使用 .Net 4.5 或更高版本(即引入“异步”时)
回答by chue x
If zzztest
is a long running operation, you can do this to run it in a background thread:
如果zzztest
是长时间运行的操作,您可以这样做以在后台线程中运行它:
async private Task<string> thr_calc(object sender, EventArgs e)
{
return await Task.Run<string>(() => zzztest());
}
The above should solve your compile errors as well.
以上内容也应该可以解决您的编译错误。
If zzztest
is NOT a long running operation, then consider NOT using await
/ async
.
如果zzztest
不是长时间运行的操作,则考虑不使用await
/ async
。
回答by Robin
On a .NET 4.0 project, I resolved 'Predefined type 'System.Runtime.CompilerServices.IAsyncStateMachine' is not defined or imported' by installing the Microsoft.Bcl.Async package from nuget. In VS's nuget package manager, search for 'bcl' and install the async-looking one.
在 .NET 4.0 项目中,我通过从 nuget 安装 Microsoft.Bcl.Async 包解决了“未定义或导入预定义类型‘System.Runtime.CompilerServices.IAsyncStateMachine’”。在 VS 的 nuget 包管理器中,搜索“bcl”并安装看起来像异步的那个。