简体   繁体   English

回到异步回调方法中的ui线程

[英]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. 目前,在这些情况下,我正在使用异步lambda进行显式的Dispatcher / Invoke,但考虑到使用async / await进行的其他所有处理,它似乎很脏。

So I guess the question is, is there something like this in C#? 所以我想问题是,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/ 您可以使用https://www.thomaslevesque.com/2015/11/11/explicitly-switch-to-the-ui-thread-in-an-async-method/中介绍的技术

Include SynchronizationContextAwaiter into your code. 在您的代码中包括SynchronizationContextAwaiter。

Somewhere in your code capture the GUI context in syncContext variable which should be available to your event handler. 您的代码中的某个地方在syncContext变量中捕获了GUI上下文,该变量应该对事件处理程序可用。

In the event handler, do 在事件处理程序中,执行

await syncContext;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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