赞
踩
C#中,工作线程无法直接在线程函数中操作UI主线程中的UI对象,必须通过线程切换到UI线程去执行相应的操作界面元素的代码。
主要有两种方法可以在工作线程中完成UI界面元素的操作:
1.Control.Invoke
2.SynchronizationContext
下面的例子同时使用了这两个方法做演示(SynchronizationContext也可以使用Send来调用UI线程中的方法委托)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace WF_SynchronizationContext_Test
{
public partial class Form1 : Form
{
private SynchronizationContext sc = null;
public delegate void ShowText(object o);
public Form1()
{
InitializeComponent();
Thread.CurrentThread.Name = "mainthread";
sc = SynchronizationContext.Current;
}
public void ShowStatus(object o)
{
this.label1.Text = string.Format("in sub thread:{0}", Thread.CurrentThread.Name);
}
private void button1_Click(object sender, EventArgs e)
{
ShowText showTxt = new ShowText(ShowStatus);
Thread thread = new Thread(o=>
{
Thread.CurrentThread.Name = "subthread";
Form1 f = o as Form1;
if (f != null)
{
f.Invoke(showTxt);
string s = Thread.CurrentThread.Name;
}
});
thread.IsBackground = true;
thread.Start(this);
}
private void button2_Click(object sender, EventArgs e)
{
Thread thread = new Thread(o =>
{
Thread.CurrentThread.Name = "subthread";
SynchronizationContext sc = o as SynchronizationContext;
if (sc != null)
{
sc.Post(ShowStatus, null);
}
string s = Thread.CurrentThread.Name;
});
thread.IsBackground = true;
thread.Start(this.sc);
}
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。