简体   繁体   中英

Get back to ui thread in async callback method

I'm migrating more and more of my code to async/await and mostly it's smooth sailing.

However sometimes I arrive at the following situation and I'm not sure how it's "meant" to work with the async/await pattern:

    private async void My_EventHandler(object sender, Event ev)
    {
        // This event is raised by a background worker thread
        // Somehow we need to go back to ui thread here
        NotifyPropertyChange(Busy); // Or any other method that should run on ui thread
        await processEventAsync(ev);
        NotifyPropertyChange(Busy);
    }

Currently I'm doing an explicit Dispatcher/Invoke with an async lambda in these cases, but it seems dirty considering how clean everything else is with async/await.

So I guess the question is, is there something like this in C#?

await SwitchToUIThread();

You can use the technique explained in https://www.thomaslevesque.com/2015/11/11/explicitly-switch-to-the-ui-thread-in-an-async-method/

Include SynchronizationContextAwaiter into your code.

Somewhere in your code capture the GUI context in syncContext variable which should be available to your event handler.

In the event handler, do

await syncContext;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM