I've read this question from Noseratio which shows a behaviour where TaskScheduler.Current
is not the same after an awaitable has finished its operation.
The answer states that :
If there is no actual task being executed, then
TaskScheduler.Current
is the same asTaskScheduler.Default
Which is true . I already saw it here :
TaskScheduler.Default
- Returns an instance of the
ThreadPoolTaskScheduler
TaskScheduler.Current
- If called from within an executing task will return the
TaskScheduler
of the currently executing task- If called from any other place will return
TaskScheduler.Default
But then I thought , If so , Let's do create an actual Task
(and not just Task.Yield()
) and test it :
async void button1_Click_1(object sender, EventArgs e)
{
var ts = TaskScheduler.FromCurrentSynchronizationContext();
await Task.Factory.StartNew(async () =>
{
MessageBox.Show((TaskScheduler.Current == ts).ToString()); //True
await new WebClient().DownloadStringTaskAsync("http://www.google.com");
MessageBox.Show((TaskScheduler.Current == ts).ToString());//False
}, CancellationToken.None, TaskCreationOptions.None,ts).Unwrap();
}
First Messagebox is "True" , second is "False"
Question:
As you can see , I did created an actual task.
I can understand why the first MessageBox yield True
. Thats becuase of the :
If called from within an executing task will return the TaskScheduler of the currently executing task
And that task does have ts
which is the sent TaskScheduler.FromCurrentSynchronizationContext()
But why the context is not preserved at the second MessageBox ? To me , It wasn't clear from Stephan's answer.
Additional information :
If I write instead (of the second messagebox ) :
MessageBox.Show((TaskScheduler.Current == TaskScheduler.Default).ToString());
It does yield true
. But why ?