代码如下:
private Thread m_thread;
private SynchronizationContext m_context;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
m_context = SynchronizationContext.Current;
}
private void button1_Click(object sender, EventArgs e)
{
m_thread = new Thread(new ThreadStart(delegate
{
while (true)
{
m_context.Post(new SendOrPostCallback(delegate
{
textBox1.Text = DateTime.Now.ToString();
}),null);
Thread.Sleep(50);
}
}));
m_thread.Start();
}
SynchronizationContext 提供各种同步模型中同步上下文的基本功能。
本文利用线程的计时器测试该功能,如果不采用m_context的Post方法,在调试系统时会提示线程同步出错问题。增加Post后,会将一个异步消息,调度到一个同步上下文。