当然是能实现的,这里有两种方式。下面的例子中,在后台现程中操作了一个名为textBox1的控件。
1、使用SynchronizationContext,这是MSDN推荐的方法,详细内容可以参考http://www.cnblogs.com/Kevin-moon/archive/2009/01/13/1374353.html
public Form1()
{
InitializeComponent();
SynchronizationContext context = SynchronizationContext.Current;
Thread thread = new Thread(new ParameterizedThreadStart(ThreadProc));
thread.Start(context);
}
private void ThreadProc(object stat)
{
SynchronizationContext context = stat as SynchronizationContext;
Random rand = new Random();
context.Post(UpdateUI, rand.Next(10, 1000));
}
private void UpdateUI(object obj)
{
this.textBox1.Text = obj.ToString();
}
2、使用Control.InvokeRequired属性,详细的说明google一下吧:
delegate void SetTextHandler(string val);
public Form1()
{
InitializeComponent();
SynchronizationContext context = SynchronizationContext.Current;
Thread thread1 = new Thread(new ThreadStart(ThreadProc1));
thread1.Start();
}
private void ThreadProc1()
{
Random rand = new Random();
SetText(rand.NextDouble().ToString());
}
private void SetText(string val)
{
if (this.textBox1.InvokeRequired)
{
SetTextHandler handler = new SetTextHandler(SetText);
textBox1.Invoke(handler, new object[] { val });
}
else
{
textBox1.Text = val;
}
}
用内置的委托也可以实现吧!
this.Invoke((ThreadStart)delegate
{
tabControl1.SelectedTab = tabItem8
});