在C#中跨线程操作控件是不允许的,有两种解决方式,实现方式都是一样的,都是通过异步和委托实现
第一种 直接使用异步和委托,如:
this.BeginInvoke(new MethodInvoker(delegate
{
//这里写要进行操作的具体代码
}
));
第二种方式,在WinForm中一部分需要操作的控件都不是当前界面上的控件,比如自定义弹出框
这个时候可以使用第二种方式,直接在控件中定义,调用控件修改数据的方法改为如下:
public void AddText(string msg, Color color)
{
if (this.InvokeRequired)
{
MsgFormShowDelegate fc = new MsgFormShowDelegate(AddText);
_instance.Invoke(fc, new object[] { msg, color });
}
else
{
this.richTextBox1.SelectionColor = color;
this.richTextBox1.Text = "随便写啥都行"+msg;
_instance.Show();
_instance.BringToFront();
}
}
这是一个自定义的弹出窗,主要的控件就是一个富文本框,这个方法就是在富文本框中添加一行信息,并将这个弹出窗显示出来,在主线程中调用这个控件,并调用这个控件中的这个方法就可以;但是这种方式需要注意:在进行异步操作之前,需要先在主线程中调用一次这个方法。
public partial class FrmMsgShow : Form
{
private static FrmMsgShow _instance = null;
public static FrmMsgShow Instance {
get {
if (_instance == null)
{
_instance = new FrmMsgShow();
}
return _instance;
}
}
private delegate void MsgFormShowDelegate(string msg, Color color);
public FrmMsgShow()
{
InitializeComponent();
this.richTextBox1.MaxLength = 5000;
}
public void AddText(string msg, Color color)
{
if (this.InvokeRequired)
{
MsgFormShowDelegate fc = new MsgFormShowDelegate(AddText);
_instance.Invoke(fc, new object[] { msg, color });
}
else
{
this.richTextBox1.SelectionColor = color;
this.richTextBox1.Text = "随便写啥都行"+msg;
_instance.Show();
_instance.BringToFront();
}
}
private void button1_Click(object sender, EventArgs e)
{
this.Hide();
}
}
这就是这一整个控件的代码,为了节省资源并且保存之前显示过的信息,是单例实现。