【发布时间】:2018-02-25 11:27:39
【问题描述】:
而不是在后台工作 - 此代码仍然冻结我的程序:
private void button_Click(object sender, RoutedEventArgs e)
{
this.Dispatcher.BeginInvoke(new Action(() =>
{
Thread.Sleep(5000);
label.Content = "Done";
}), DispatcherPriority.Normal);
}
我已经尝试过线程/任务,线程示例:
private void button_Click(object sender, RoutedEventArgs e)
{
var t = new Thread(new ThreadStart(runtask));
t.Start();
}
private void runtask()
{
this.Dispatcher.BeginInvoke(new Action(() =>
{
Thread.Sleep(5000);
label.Content = "Done";
}), DispatcherPriority.Normal);
}
任务示例:
private void button_Click(object sender, RoutedEventArgs e)
{
Task.Run(() =>
{
Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, new Action(() =>
{
Thread.Sleep(5000);
label.Content = "Done";
}));
});
}
我的程序仍然冻结。有什么建议吗?
【问题讨论】:
-
是什么让你觉得
BeginInvoke在后台运行它? -
如果你调用 Invoke,你实际上是在主线程上..
-
@rhonin 文档意味着它是异步的从调用线程的角度来看。从UI线程的角度来看,这绝对是一个同步操作。
-
是的,正是……
标签: c# wpf multithreading task dispatcher