Hi @ David Thielen , Welcome to Microsoft Q&A,
Updated by Bruce :
Here is a good explanation:
https://blog.stephencleary.com/2012/07/dont-block-on-async-code.html
it does complete. it the notification of completion that is in a thread deadlock (locked thread context), which is why using .Result() is not recommended from the UI thread.
sample UI deadlock code:
private void btnDeadLock_Click(object sender, EventArgs e)
{
Func<Task<string>> DeadlockCode = async () =>
{
// lock context
await Task.Delay(1000);
return "done";
};
var value = DeadlockCode().Result;
}
a more safe way. (no deadlock):
private void btnNoDeadLock_Click(object sender, EventArgs e)
{
Func<Task<string>> NoDeadlockCode = async () =>
{
// don't lock context
await Task.Delay(1000).ConfigureAwait(false);
return "done";
};
var value = NoDeadlockCode().Result;
}
note: you should fire and forget. if the UI must be updated be sure to use thread marshaling via invoke() as UI elements can only be updated from the UI thread.
When you mark a method as async
, it allows you to use the await
keyword inside the method. This marking does not make the method run asynchronously by itself; it just enables the use of await
.
When you use await
on a task (e.g., Task.Delay(1)
), the method will asynchronously wait for that task to complete. The control is returned to the caller of the async
method, and the method continues execution once the awaited task completes.
By default, await
captures the current synchronization context and tries to resume on that context. In a UI application, this means resuming on the UI thread. In a console application or background thread, it might mean resuming on the thread pool.
If the synchronization context is busy (e.g., UI thread is blocked or doing other work), the task might not resume immediately after the delay, causing what looks like a block.
ConfigureAwait(false)
can help avoid capturing the synchronization context and prevent deadlocks.
Best Regards,
Jiale
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.