Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can i force await to continue on the same thread?

await does not guarantee continuation on the same task for spawned tasks:

private void TestButton_Click(object sender, RoutedEventArgs e)
{
    Task.Run(async () =>
    {
        Debug.WriteLine("running on task " + Task.CurrentId);
        await Task.Delay(TimeSpan.FromMilliseconds(100));
        Debug.WriteLine("running on task " + Task.CurrentId);
    });
}

The output of this is:

running on task 1
running on task

so we can see that not only the execution has moved to another task, but also to the UI-thread. How can i create a dedicated task, and enforce await to always continue on this task? Long-running tasks don't do this either.

I have seen several SynchronizationContext implementations, but so far none of them worked, in this case because it uses threads and System.Threading.Thread is not available for uwp.

like image 448
Benni Avatar asked Mar 13 '17 08:03

Benni


People also ask

Is async await on the same thread?

The async and await keywords don't cause additional threads to be created. Async methods don't require multithreading because an async method doesn't run on its own thread. The method runs on the current synchronization context and uses time on the thread only when the method is active.

Does await make it synchronous?

Async/await helps you write synchronous-looking JavaScript code that works asynchronously. Await is in an async function to ensure that all promises that are returned in the function are synchronized. With async/await, there's no use of callbacks.

Does await pause the thread?

Asynchronous Methods When the executing thread reaches an await expression, it hits the “pause” button and the method execution is suspended.

Does await task delay block thread?

await Task. Delay(1000) doesn't block the thread, unlike Task. Delay(1000).


1 Answers

so we can see that not only the execution has moved to another task, but also to the UI-thread.

No, it's not on the UI thread. It's just technically not on a task, either. I explain why this happens in my blog post on Task.CurrentId in async methods.

How can i create a dedicated task, and enforce await to always continue on this task? Long-running tasks don't do this either.

You're on the right track: you need a custom SynchronizationContext (or a custom TaskScheduler).

I have seen several SynchronizationContext implementations, but so far none of them worked, in this case because it uses threads and System.Threading.Thread is not available for uwp.

Try out mine. It should work on UWP 10.0.

like image 155
Stephen Cleary Avatar answered Nov 15 '22 00:11

Stephen Cleary