简体   繁体   English

UWP从在不同线程中运行的任务更新UI控件

[英]UWP update UI control from a task running in a different thread

UI has a label named lblMyLabel. UI有一个名为lblMyLabel的标签。 It's bound to a view model MyViewModel. 它绑定到视图模型MyViewModel。

A task is running on a different thread which pulls message from a service.( for example) 任务正在不同的线程上运行,该线程从服务中提取消息。(例如)

When a this task receives a specific value it should update the UI label with it. 当此任务收到特定值时,应使用此值更新UI标签。

I always get a error that it was Marshalled in a different thread . 我总是得到一个错误,它被编组在另一个线程中。

When you want to update UI,you should run on the UI's dispatcher thread.You can call Dispatcher.RunAsync to back onto the UI's dispatcher thread. 当您要更新UI时,应在UI的调度程序线程上运行。可以调用Dispatcher.RunAsync返回到UI的调度程序线程。

private void Button_Click(object sender, RoutedEventArgs e)
{
    //Start a Task
    Task t = Task.Factory.StartNew(() => {
        int i = 0;
        for (i = 0; i <= 1000; i++)
        { 
        }
        //Back onto the UI thread
        var a = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
        {
            //Update UI
            MyTextBlock.Text = "Update";
        });
    });
}

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

相关问题 使用 Winforms 中的后台线程更新 UI 中的控件 - update a control in UI with running background Thread in Winforms 从运行的线程更新UI - Update UI from running thread 从不同类中的不同线程更新UI - Update UI from a different thread in a different class 当UI在Task.Wait()上为当前状态时,使用Dispatcher强制UI线程更新控件。 - Using Dispatcher to force UI thread to update a control when UI is current on Task.Wait(); 除了Android中的主线程之外,是否可以从不同的线程更新UI? - Is it possible to update the UI from different thread besides the Main Thread in Android? 它是错误还是功能? 在某些情况下,可以从不在UI线程上运行的任务访问UI线程 - Is it a bug or a feature? In some cases it is possible to access the UI thread from a task not running on the UI thread 无法从非UI线程更新wpf控件 - cannot update wpf control from non UI thread WPF从同一线程中的另一个窗口更新一个窗口的UI控件 - WPF update UI control of a window from another window in the same thread 尝试使用更改来自其他线程的UI控件属性。 要求调用 - Trying to change UI control property from different thread using . InvokeRequired 如何从另一个类中运行的另一个线程更新UI - How to update UI from another thread running in another class
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM