- 在system.componentModel 下有一个抽象类: SynchronizationContext 他使得Thread Marshaling得到泛型化。
- 针对移动 桌面 等富客户端应用api 他们都定义和实例化了synchronzzationContext的子类
- 可以通过静态属性Synchronizationcontext.Current 来获取(当运行在UI线程是)
- 捕获改属性后你可以供任何子线程通过Post方法想UI主线程发送数据。
- 调用Post就相当于调用Dispath 或Control 上面的BeginInvoke 方法。还有一个send方法相当于BeginInvoke
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
{
private static SynchronizationContext UIContext;
public MainWindow()
{
InitializeComponent();
UIContext = SynchronizationContext.Current;
}
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);
UIContext.Post(_ => { textBlock1.Text = str; },null);
}
}
}