一. 子线程的数据,赋给主线程的控件
1.实例化线程
//消息线程
Thread receiveThread = new Thread(new ThreadStart(ReceiveMessageThread));//ReceiveMessageThread为线程的回调方法receiveThread.IsBackground = true; //设置线程为后台线程.(设置成后台线程后,前台主线程关闭,则此后台线程将强制关闭)receiveThread.Start(); //启动线程
2. 线程回调方法
//定义委托,用于后台线程与主线程的数据交互
public delegate void FuncHandle(string strMessage);private void ReceiveMessageThread()
{ while (true) { Thread.Sleep(1000); FuncHandle fh = new FuncHandle(SetFormReceiveMessage);//实例化委托 if (this.InvokeRequired) { this.BeginInvoke(fh, new object[] { "方法参数值strMessage"}); } } }3. 与主线程交互
//显示接收的消息
private void SetFormReceiveMessage(string strMessage){this.txtMessageBox.Text = strMessage;
}
二.子线程访问主线程的静态变量
//消息线程
Thread threadTimer = new Thread(new ThreadStart(SetServerDatetime));threadTimer.IsBackground = true;threadTimer.Start();//设定时间并每隔一秒更新一次
private void SetServerDatetime() { while (true) { Thread.Sleep(1000);//PublicValue.serverDatetime 为主线程的静态变量(保存时间字符串型)
string ttk = Convert.ToDateTime(Convert.ToString(PublicValue.serverDatetime)).AddSeconds(1d).ToString(); //改变时间变量 Interlocked.Exchange<string>(ref PublicValue.serverDatetime, ttk); } }