Asyc Method Waiting for Task.Run () Never Terminates "

I have a method that is defined as

public async Task SomeAsyncMethod() { DoSomeStuff(); await Task.Run(() => { DoSomeSyncStuff(); DoSomeOtherSyncStuff(); }); var someDebugVariable = "someDebugValue"; } 

The method itself does what it should do, and everything works fine. However ... it seems that the "external" async Task never ends.

Example: when I call it as follows

 public void CallerMethod() { Task t = SomeAsyncMethod(); t.Wait(); } 

t.Wait() never completes. Also: if I put a breakpoint when assigning someDebugVariable , it never hits.

I could add that DoSomeSyncStuff and DoSomeOtherSyncStuff really do what they assume, and debugging through them tells me that they both complete.

To prove my point, I changed my method as follows, and the results remained the same.

 public async Task SomeAsyncMethod() { DoSomeStuff(); await Task.Run(() => { /* DoSomeSyncStuff(); DoSomeOtherSyncStuff(); */ var a = 2; var b = 3; var c = a + b; }); var someDebugVariable = "someDebugValue"; } 

EDIT

I tried to delete everything except await Task.Run , and did not change anything. This is still not complete.

The application is a WPF application. The thread of the calling thread is the user interface thread.

What am I missing here?

+4
source share
1 answer

Calling t.Wait () causes a dead end, and also makes the asynchronous call completely pointless. I believe that if you change the code to

 await Task.Run(() => { // ... }).ConfigureAwait(false); 

You can fix the deadlock and continue the code, but you really need to get rid of the t.Wait () call. All that needs to be done with the results of calls to the synchronization functions should be done after the expected task, and not after the async function call.

In more detail: task.Wait () blocks all execution of the main thread during task execution. When the wait task is executed, it tries to redirect the main thread, but the main thread is blocked! Since A is waiting for B and B is waiting for A, you get a dead end.

See: http://blog.stephencleary.com/2012/07/dont-block-on-async-code.html

+8
source

Source: https://habr.com/ru/post/1241602/


All Articles