摘自stackoverflow:https://stackoverflow.com/questions/14703698/invokedelegate
If you want to modify a control ,it must be done in the thread in which the control was created. This Invoke method allows you to execute methods in the associated thread( the thread that owns the control's underlying window handle)
/**************************************************************************************************************
一 第一种方式
public delegate void AddDelegate(int i);
public void AddHandle(int i)
{
AddDelegate AddDe = new AddDelegate(AddFunction);
richTextBox1.Invoke(AddDe,new object[]{i});
}
public void AddFunction(int i)
{
this.richTextBox1.SelectionColor = Color.Blue;//用richTextBox的SelectionColor属性可以让每行颜色各异
this.richTextBox1.AppendText("Value in second thread is : " + i.ToString() + "\r\n");
}
二 第二种方式(倾向于使用第二种,lamba表达式更为简洁)
void AddHandle(int i)
{
Action action = () =>
{
this.richTextBox1.SelectionColor = Color.Red;
this.richTextBox1.AppendText("Value in second thread is : " + i.ToString() + "\r\n");
};
richTextBox1.BeginInvoke(action);
}