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?
The last way to handle an error with async/await is called a higher order function. We have talked about this a couple of times now. A higher order function is a function that returns another function. The way it works is you go ahead and define all of your functions, just as if you were never to have any errors.
If a promise resolves normally, then await promise returns the result. But in the case of a rejection, it throws the error, just as if there were a throw statement at that line. In real situations, the promise may take some time before it rejects. In that case there will be a delay before await throws an error.
To recap: Throwing error from an async function won't spit out a "plain exception". Async functions and async methods always return a Promise, either resolved or rejected. To intercept exceptions from async functions you must use catch() .
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With