Confused by dispatcher and asynchronous

I am making an application for a Windows 8.1 tablet and I am using the async keyword quite strongly. My understanding of the async keyword is that although it seems to be in sync with the programmer, there is no guarantee that you will work on the same thread when your wait is over.

In my code behind the file, I use the dispatcher to run any UI updates in the UI thread. Each example I found indicates that it is good practice to use a callback script, but I did not mention this when using async. In my understanding of async, it would seem that I would need to use the dispatcher whenever I want to update the interface after any waiting call.

I tried to be more clear by adding my understanding to the code below.

private void SomeEventHandler(object sender, RoutedEventArgs e)
{
    UpdateUI(); //This should run in my UI thread
    await Foo(); //When Foo returns I have no guarantee that I am in the same thread
    UpdateUI(); //This could potentially give me an error
    await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
    {
        UpdateUI(); //This will run in the UI thread
    });
}

I only need access to the UIContext, and the thread doesn't matter? It would be great if someone could clarify this to me.

+4
source share
1 answer

My understanding of the async keyword is that although it seems to be in sync with the programmer, there is no guarantee that you will work on the same thread when your wait is over.

... , async, ( ), , , .ConfigureAwait(false).

, ThreadPool ( , , ).

, :

private void SomeEventHandler(object sender, RoutedEventArgs e)
{
    UpdateUI(); //This should run in my UI thread
    await Foo(); //When Foo returns I am still in the UI thread
    UpdateUI(); //This will work fine, as I'm still in the UI thread

    // This is useless, since I'm already in the UI thread ;-)
    await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
    {
        UpdateUI(); //This will run in the UI thread
    });
}
+8

Source: https://habr.com/ru/post/1541349/


All Articles