I have stumbled upon a strange behavior of async-await.
Example code:
public class foo
{
public async static Task<myobj> method1()
{
var result = await method2();
return result;
}
private async static Task<myobj> method2()
{
// omitted for brevity.
}
}
public class bar
{
public void caller()
{
var result = foo.method1().Result;
pass(result);
}
}
This freezes the UI. The solution is to implement async-await on caller().
But how about this:
public class foo
{
public static myobj method1()
{
var result = method2().Result;
return result;
}
private async static Task<myobj> method2()
{
// omitted for brevity.
}
}
public class bar
{
public void caller()
{
var result = foo.method1();
pass(result);
}
}
This works freely.
What is different with private call vs. the one made to upstream method from other class?
As I mentioned in the comment, the first case is described in great details by Stephen Cleary in his blog .
The deadlock occurs at await method2()
. The await
continuation was posted to the UI thread's synchronization context via SynchronizationContext.Post
. But the UI thread is already blocked waiting at this line: foo.method1().Result
. The message pump is blocked and the continuation callback never gets pumped and invoked, deadlock.
In the second case, I don't see await
anywhere. Ie, the code as you shown it doesn't do any asynchrony. I guess that's why it works.
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.