Regarding this piece of code:
static async Task<string> testc() { Console.WriteLine("helo async " + Thread.CurrentThread.ManagedThreadId); await Task.Run(() => { Thread.Sleep(1000); Console.WriteLine("task " + Thread.CurrentThread.ManagedThreadId); }); Console.WriteLine("callback "+Thread.CurrentThread.ManagedThreadId); return "bob"; } static void Main(string[] args) { Console.WriteLine("helo sync " + Thread.CurrentThread.ManagedThreadId); testc(); Console.WriteLine("over" + Thread.CurrentThread.ManagedThreadId); Thread.Sleep(2000); Console.ReadLine(); }
I get the following output:
helo sync 10 helo async 10 over10 task 11 callback **11**
This is normal: after waiting, part of the code is executed in the same thread as the task itself.
Now, if I do this in a WPF application:
private void Button_Click_1(object sender, RoutedEventArgs e) { Console.WriteLine("helo sync " + Thread.CurrentThread.ManagedThreadId); testc(); Console.WriteLine("over" + Thread.CurrentThread.ManagedThreadId); Thread.Sleep(2000); Console.ReadLine(); }
It generates the following output:
helo sync 8 helo async 8 over8 task 9 callback **8**
Where we can see the code after waiting in the user interface thread. Well, that's great, as it allows you to manipulate observable collections, etc. But I was wondering: "Why?" "How could I do the same?" Is this related to the behavior of TaskScheduler? Is this hardcoded in the .NET Framework?
Thanks for any idea you can send.
Kek
source share