简体   繁体   English

等待/异步参考错​​误

[英]Await/async reference error

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! 但这给了我错误,每个字符串包含单词async / await! Im using russian version of ms vs express 2012 for windows desktop, so here is the translation of errors: 我正在使用俄语版的MS vs Express 2012 for Windows桌面,因此这是错误的翻译:

Cannot find all types required by the 'async' modifier. 找不到“异步”修饰符所需的所有类型。 Are you targeting the wrong framework version, or missing a reference to an assembly? 您是针对错误的框架版本,还是缺少对程序集的引用?

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. 我以前尝试过使用async / await,并且效果很好,现在我做的都一样,而事实并非如此。 What I am missing? 我缺少什么?

  • In thr_calc, use: 在thr_calc中,使用:

     return zzztest() 
  • Also, make sure you've set your project to use .Net 4.5 or later (that's when "async" was introduced) 另外,请确保已将项目设置为使用.Net 4.5或更高版本(即引入“异步”的时候)

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. 在.NET 4.0项目中,我通过从nuget安装Microsoft.Bcl.Async程序包解决了“未定义或导入'预定义类型'System.Runtime.CompilerServices.IAsyncStateMachine'”的问题。 In VS's nuget package manager, search for 'bcl' and install the async-looking one. 在VS的nuget程序包管理器中,搜索“ bcl”并安装外观类似异步的程序。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM