'await' works, but calling task.Result hangs/deadlocks
回答1
Acquiring a value via an async method:
var result = Task.Run(() => asyncGetValue()).Result;
Syncronously calling an async method
Task.Run( () => asyncMethod()).Wait();
No deadlock issues will occur due to the use of Task.Run.
回答2
You're running into the standard deadlock situation that I describe on my blog and in an MSDN article: the async
method is attempting to schedule its continuation onto a thread that is being blocked by the call to Result
.
In this case, your SynchronizationContext
is the one used by NUnit to execute async void
test methods. I would try using async Task
test methods instead.
回答3
An addition to the answer given by @HermanSchoenfeld. Unfortunately the quote below is not true:
No deadlock issues will occur due to the use of Task.Run.
public String GetSqlConnString(RubrikkUser user, RubrikkDb db)
{
// deadlock if called from threadpool,
// works fine on UI thread, works fine from console main
return Task.Run(() =>
GetSqlConnStringAsync(user, db)).Result;
}
The execution is wrapped inside a Task.Run, this will schedule the task on the threadpool the block the calling thread. This is okay, as long as the calling thread is not a threadpool thread. If the calling thread is from the threadpool then the following disaster happens: A new task is queued to the end of the queue, and the threadpool thread which would eventually execute the Task is blocked until the Task is executed.
In library code there is no easy solution as you cannot assume under what context your code is called. The best solution is to only call async code from async code, blocking sync APIs from sync methods, don’t mix them.
Source:
https://medium.com/rubrikkgroup/understanding-async-avoiding-deadlocks-e41f8f2c6f5d
标签:Task,Run,thread,await,hangs,calling,task,Result,async From: https://www.cnblogs.com/chucklu/p/17199030.html