经常要考虑的,后台的耗时操作不要卡死主界面的问题。
<StackPanel VerticalAlignment="Center">
<Label x:Name="lblHello">欢迎你光临WPF的世界!</Label>
<Button Name="btnThd" Click="btnThd_Click" >多线程同步调用</Button>
<Button Name="btnAppBeginInvoke" Click="btnAppBeginInvoke_Click" >BeginInvoke 异步调用</Button>
</StackPanel>
Behind Code:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void ModifyUI()
{
//// 模拟一些工作正在进行
//Thread.Sleep(TimeSpan.FromSeconds(2));
//lblHello.Content = "欢迎你光临WPF的世界,Dispatcher";
// 模拟一些工作正在进行
Thread.Sleep(TimeSpan.FromSeconds(3));
this.Dispatcher.Invoke(DispatcherPriority.Normal, (ThreadStart)delegate ()
{
lblHello.Content = "欢迎你光临WPF的世界,Dispatche 同步方法 !!";
});
}
private void btnThd_Click(object sender, RoutedEventArgs e)
{
Thread thread = new Thread(ModifyUI);
thread.Start();
}
private void btnAppBeginInvoke_Click(object sender, RoutedEventArgs e)
{
new Thread(() =>
{
Thread.Sleep(TimeSpan.FromSeconds(3));
Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
new Action(() =>
{
//Thread.Sleep(TimeSpan.FromSeconds(3)); // 放这里还是会卡 UI 界面线程
this.lblHello.Content = "欢迎你光临WPF的世界,Dispatche 异步方法!!" + DateTime.Now.ToString();
}));
}).Start();
}
}
这样调用,是不会卡主界面的。