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:
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:
Predefined type 'System.Runtime.CompilerServices.IAsyncStateMachine' is not defined or imported
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?
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)
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.
If zzztest
is a long running operation, you can do this to run it in a background thread:
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
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.