[英]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.