Difference between putting code at the end of a Task that is awaited versus putting code after the await:

StackOverflow https://stackoverflow.com/questions/22150173

  •  19-10-2022
  •  | 
  •  

Вопрос

Should this block of code...

async void SomeMethodAsync() {
    this.IsDoingLongRunningWork = true;
    await Task.Run(() => 
    {
        DoLongRunningWork();
        this.IsDoingLongRunningWork = false;
    });
}

...behave differently than this block of code...

async void SomeMethodAsync() {
    this.IsDoingLongRunningWork = true;
    await Task.Run(() => 
    {
        DoLongRunningWork();
    });
    this.IsDoingLongRunningWork = false;
}

...?

Это было полезно?

Решение

Well they may well be executed in different threads, for one thing. If IsDoingLongRunningWork affects a user interface (for example) then it should probably only be changed in the UI thread, in which case the first code is incorrect (the new task will run in a thread-pool thread) and the second code is correct (assuming the method is called from a UI thread).

Другие советы

BTW, you have a syntax error in your code. You are missing ); for each await statement.

The answer depends a lot on whether there is a synchronization context. For example, I am pretty sure that if this code is running in a Console application, the code after the await statement could be executed in a different thread than the code before await. However, in a Windows application (which uses a UI thread synchronization context), your code will return to the main UI thread after await finishes (assuming the code before await was executing on the main UI thread).

Without more context, the answer is yes: The code is different. At the very least, make sure IsDoingLongRunningWork is thread-safe.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top