Why am I still on the main topic when I pointed out ConfigureAwait (false)?

I am trying to understand how async / await works. I have a text block in a WPF window that binds a StringBlockContent string property and a button that fires when I click ChangeText ().

Here is my code:

public async void ChangeText() { string mystring = await TestAsync(); this.TextBlockContent= mystring; } private async Task<string> TestAsync() { var mystring = await GetSomeString().ConfigureAwait(false); mystring = mystring + "defg"; return mystring; } private Task<string> GetSomeString() { return Task.Run(() => { return "abc"; }); } 

From my readings, I realized that ConfigureAwait is set to false, allowing me to indicate that I do not want to save the current context for the "rest" of the task that should be performed after the wait keyword.

After debugging, I understand that when I have this code, sometimes the code runs in the main thread after the line: await GetSomeString (). ConfigureAwait (false); while I specifically added configure.

I would expect that he will always work in a different thread than the one in which he was before he introduced the task.

Can someone help me understand why?

Many thanks

+7
c # wpf async-await
source share
1 answer

It is possible that the task you are completing ends immediately, which means that await does not even need to plan a continuation. The async method only plans to continue when necessary; if you wait for something that has already been completed, it just continues - in the same stream.

ConfigureAwait is a hint that you do not need to continue in the same context; it is not a requirement that you should not continue to work in the same context.

If you change your task to something that is not completed right away - for example. call Thread.Sleep(1000) (which of course you usually didn’t), I expect you to see a change in behavior.

It is possible that I missed something else and that this is not the cause of the problem, but at least it is worth trying it first.

+12
source share

All Articles