跨线程调用控件,修改控件的属性,比如有一个text控件,用来显示消息
需要使用begininvoke
网上随便找了一个代码,应该是靠谱的,需要使用委托,判断控件是否invokeRequired
用委托,具体代码如下~:
public delegate void MyInvoke(string str);
private void button9_Click(object sender, EventArgs e)
{
Thread t = new Thread(new ThreadStart(fun));
t.Start();
}
private void fun()
{
//_myInvoke("dddd");
SetText("ddd");
}
private void SetText(string s)
{
if (textBox6.InvokeRequired)
{
MyInvoke _myInvoke = new MyInvoke(SetText);
this.Invoke(_myInvoke, new object[] { s });
}
else
{
this.textBox6.Text = s;
}
}
最近发现的牛逼方法
txtbox.Invoke((MethodInvoker)delegate()
{
//在这里写处理方法就可以了
});
逐步 txtbox.Invoke();
txtbox.Invoke((MethodInvoker)delegate(){});
#region 程序集 System.Windows.Forms.dll, v4.0.30319
// C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\System.Windows.Forms.dll
#endregion
using System;
namespace System.Windows.Forms
{
// 摘要:
// 表示一个委托,该委托可执行托管代码中声明为 void 且不接受任何参数的任何方法。
public delegate void MethodInvoker();
}
MethodInvoker 提供一个简单委托,该委托用于调用含 void 参数列表的方法。
在对控件的 Invoke 方法进行调用时或需要一个简单委托又不想自己定义时可以使用该委托。
下面的代码示例演示如何使用 MethodInvoker 以调用更新应用程序窗体的标题栏的方法。
public partial class Form1 : Form
{
public Form1()
{
// Create a timer that will call the ShowTime method every second.
var timer = new System.Threading.Timer(ShowTime, null, 0, 1000);
}
private void ShowTime(object x)
{
// Don't do anything if the form's handle hasn't been created
// or the form has been disposed.
if (!this.IsHandleCreated && !this.IsDisposed)
return;
// Invoke an anonymous method on the thread of the form.
this.Invoke((MethodInvoker) delegate
{
// Show the current time in the form's title bar.
this.Text = DateTime.Now.ToLongTimeString();
});
}
}