Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I still on the Main Thread when I specified ConfigureAwait(false)?

I am trying to understand how async/await keywords works. I have a textblock on a WPF window bind to a TextBlockContent string property and a button which trigger on 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 understood that ConfigureAwait set to false would allow me to specify that I do not want to save the Current context for the "rest" of the Task that needs to be executed after the await keyword.

After debugging i realize that when i have this code, sometime the code is running on the Main thread after the line : await GetSomeString().ConfigureAwait(false); while i specifically added the configure await.

I would have expected it to always run on a different thread that the one it was in before it entered the Task.

Can someone help me understand why?

Thank you very much

like image 769
K. L. Avatar asked Oct 19 '13 19:10

K. L.


1 Answers

It could well be that the task you're running is completing immediately - which means that the await doesn't even need to schedule a continuation. An async method only schedules a continuation when it needs to; if you await something which has already completed, it just keeps going - in the same thread.

ConfigureAwait is a hint that you don't need to continue in the same context; it's not a requirement that you mustn't continue on the same context.

If you change your task to something that doesn't complete immediately - e.g. call Thread.Sleep(1000) (which of course you wouldn't normally do) I'd expect you to see a change in behaviour.

It's possible that I've missed something else and that this isn't the cause of the problem, but it would at least be worth trying that first.

like image 119
Jon Skeet Avatar answered Sep 22 '22 13:09

Jon Skeet