- 在WPF WinFrm 等类型程序,如果在主线程执行耗时的操作,就会导致整个程序无响应。
- 针对这样比较耗时的操作,一种做法就是启用一个work线程,操作完成后更新到UI界面上。
- 富客户端应用模型通常是: UI元素和控件只能从他们的线程访问(通常就是主线线程UI)
综上所述: 如果想夸线程操作,就需要使用invoke (可以获取 返回值)方法或者beginInvoke方法。把方法执行交给所述对象线程。这样做的好处是,线程之间的安全防护,自己线程的东西自己管理和操作,你要啥或者想操作请交付给我执行。
如果不需要返回值,beginInvoke/RunAsync 更可取,因为他们不会阻塞调用方,也不会引入死锁。
For text WPF code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Threading;
namespace WPFMgs
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
new Thread(Work).Start();
}
void Work()
{
Thread.Sleep(5000);
//this.textBlock1.Text = "Wpftextbox";
UpDataMgs("Wpftextbox");
}
void UpDataMgs(string str)
{
Action action =()=>{textBlock1.Text=str;};
Dispatcher.BeginInvoke(action);
}
}
}