下面这段代码怎么才能保证线程执行完了,主线程再执行,请测试通过了再说。
因为这个比较特殊,线程中要访问控件,就使得次程要切换到主线访问控件。所以
使用 thread.Join(), ManualResetEvent 等方法 都会使程序死掉。
一个Form 窗体,btnTest 按钮 txtMsg文本框
public partial class Form1 : Form { Thread thread; public Form1() { InitializeComponent(); } private void btnTest_Click(object sender, EventArgs e) { thread = new Thread(new ThreadStart(DoWork)); thread.Start(); //...... txtMsg.Text = "完成"; } void DoWork() { SetText("线程运了。"); } delegate void SetTextHandler(string msg); private void SetText(string msg) { if (txtMsg.InvokeRequired) { SetTextHandler d = new SetTextHandler(SetText); object val = (object)msg; this.Invoke(d, val); } else { txtMsg.Text += "\r\n" + msg; } } }
public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btnClick_Click(object sender, EventArgs e) { var callback = new Action(CallBack); var thread = new Thread(DoSomething); thread.Start(callback); } private void DoSomething(object obj) { var delegateMethod=new SetText(Set); this.Invoke(delegateMethod, "楼主,干活好累!!!"); Thread.Sleep(2000);//模拟延时。 (obj as Action)(); } private void CallBack() { var delegateMethod = new SetText(Set); this.Invoke(delegateMethod, "楼主,干完了!!!"); } private delegate void SetText(string msg); private void Set(string message) { this.lblMsg.Text = message; } }