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

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;
}

...?

Jon Skeet
people
quotationmark

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).

people

See more on this question at Stackoverflow