C#的线程中如何操作控件?
C#的线程中如何操作控件?比如progressbar,text什么的?谢谢
[解决办法]
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;
using System.Data.SqlClient;
using System.Collections;
namespace AutoMessager
{
delegate void myDelegate();
delegate void SetTextCallback(string text);
public partial class frmAutoMsg : Form
{
event myDelegate myEvent;
string connStr = string.Empty;
Thread thd;
//private Icon eyeIcon;
//private NotifyIconEx notifyIconA;
//private NotifyIconEx notifyIconB;
private bool canClosed = false;
public frmAutoMsg()
{
this.ShowInTaskbar = false;
InitializeComponent();
//eyeIcon = new Icon(GetType(), "EYE.ICO ");
notifyIcon1.ContextMenu = contextMenuB;
}
private void SetText(string text)
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (this.txtMsgStatus.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
this.txtMsgStatus.Text += text;
}
}
private void frmAutoMsg_Load(object sender, EventArgs e)
{
connStr = System.Configuration.ConfigurationManager.AppSettings[ "ConnString "];
thd = new Thread(new ThreadStart(doEvent));
thd.IsBackground = true;
thd.Start();
//doEvent();
//notifyIcon1.Visible = true;
}
/// <summary>
///
/// </summary>
void UpUserState()
{
SqlConnection conn = null;
DateTime now = DateTime.Now;
SqlTransaction tran = null;
SqlDataReader dr = null;
try
{
//--- 数据操作忽略
SetText( "\r\n系统提示: 职员合同消息更新成功!\r\n ");
SetText( "执行时间: " + now.ToString( "yyyy-MM-dd HH:mm:ss ") + "\r\n ");
}
catch (Exception ex)
{
dr.Close();
tran.Rollback();
SetText( "\r\n系统错误: 职员合同消息更新错误: " + ex.Message + "\r\n ");
SetText( "执行时间: " + now.ToString( "yyyy-MM-dd HH:mm:ss ") + "\r\n ");
}
finally
{
dr.Close();
conn.Close();
conn.Dispose();
}
}
/// <summary>
///
/// </summary>
void UpCaiGou()
{
SqlConnection conn = null;
DateTime now = DateTime.Now;
SqlTransaction tran = null;
SqlDataReader dr = null;
try
{
//--- 数据操作忽略
SetText( "系统提示: 合同采购消息更新成功!\r\n ");
SetText( "执行时间: " + now.ToString( "yyyy-MM-dd HH:mm:ss ") + "\r\n ");
}
catch (Exception ex)
{
dr.Close();
tran.Rollback();
SetText( "系统错误: 合同采购消息更新错误: " + ex.Message + "\r\n ");
SetText( "执行时间: " + now.ToString( "yyyy-MM-dd HH:mm:ss ") + "\r\n ");
}
finally
{
dr.Close();
conn.Close();
conn.Dispose();
}
}
/// <summary>
///
/// </summary>
void GetMoney()
{
SqlConnection conn = null;
DateTime now = DateTime.Now;
try
{
//--- 数据操作忽略
SetText( "系统提示: 供货付款消息更新成功!\r\n ");
SetText( "执行时间: " + now.ToString( "yyyy-MM-dd HH:mm:ss ") + "\r\n ");
}
catch (Exception ex)
{
SetText( "系统错误: 供货付款消息更新错误: " + ex.Message + "\r\n ");
SetText( "执行时间: " + now.ToString( "yyyy-MM-dd HH:mm:ss ") + "\r\n ");
}
finally
{
conn.Close();
conn.Dispose();
}
}
void doEvent()
{
//int weather = int.Parse(weatherTime.Text);
//int del = int.Parse(fileTime.Text);
//if(weather < 1 || weather > 24 || del < 1 || del > 24)
//{
//MessageBox.Show( "时间输入有错! ");
//button1.Enabled = true;
//return ;
//}
while (true)
{
//DateTime now = DateTime.Now;
int i = DateTime.Now.Hour;
if (i > 2 && i < 4)
{
myEvent = new myDelegate(UpUserState);
myEvent += new myDelegate(UpCaiGou);
// myEvent += new myDelegate(GetMoney);
}
//if (now.Hour == 3)
//{
// myEventB = new myDelegate(deltemp);
//}
//if (myEventA != null) myEventA();
//if (myEventB != null) myEventB();
if (myEvent != null)
{
myEvent();
myEvent = null;
}
Application.DoEvents();
Thread.Sleep(6000000); //每100分钟检查一次时间
}
}
private void frmAutoMsg_FormClosing(object sender, FormClosingEventArgs e)
{
if (canClosed == false)
{
e.Cancel = true;
this.Hide();
this.Visible = false;
//this.
}
}
private void menuItem2_Click(object sender, EventArgs e)
{
this.ShowInTaskbar = true;
this.Show();
this.Visible = true; //恢复主窗体
}
private void menuItem1_Click(object sender, EventArgs e)
{
canClosed = true;
Application.Exit();
}
private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
{
this.ShowInTaskbar = true;
this.Show();
if (this.Visible == false)
{
this.Visible = true;
}
}
private void btnClear_Click(object sender, EventArgs e)
{
this.txtMsgStatus.Text = " ";
}
private void btnUpMsg_Click(object sender, EventArgs e)
{
myEvent = new myDelegate(UpUserState);
myEvent += new myDelegate(UpCaiGou);
//myEvent += new myDelegate(GetMoney);
if (myEvent != null)
myEvent();
}
}
}
[解决办法]
如果控件不是在线程内创建的,就用invoke,或者用事件
[解决办法]
方法1 例子
//更新ListBox信息
public delegate void UpdateListBoxCallback();
//更新用户列表
private void UpdateClientListControl()
{
if (InvokeRequired)
{
listBoxClientList.BeginInvoke(new UpdateListBoxCallback(UpdateClientList), null);
}
else
{
//创建该控件的主线程直接更新信息列表
UpdateClientList();
}
}
//更新代码在这里
public void UpdateClientList()
{
listBoxClientList.Items.Clear();
for (int index = 0; index < WorkerSocketList.Count; index++)
{
string clientKey = Convert.ToString(index + 1);
Socket workerSocket = (Socket)WorkerSocketList[index];
if (workerSocket != null)
{
//将连接着服务器的客户添加到客户列表中
if (workerSocket.Connected)
{
listBoxClientList.Items.Add(clientKey);
}
}
}
}
方法2 例子
public delegate void ShowMacInList(ListBox listBox, object obj);
public event ShowMacInList ShowAllRresultInList;
//链接
this.ShowAllRresultInList += new ShowMacInList(RWOL_ShowAllRresultInList);
//
void RWOL_ShowAllRresultInList(ListBox listBox, object obj)
{
try
{
this.BeginInvoke(new ShowMacInList(ShowResult),
new object[] { listBox, obj });
}
catch
{
}
方法2效率要高点
[解决办法]
.net2.0 在子线程操作主线程创建的控件时有些时候会有异常
请参考 ISynchronizeInvoke 的msdn
或google 很多的