private void DoWork() {
Thread t = new Thread( new ThreadStart( this.DoSomething));
t.Start();
}
private void DoSomething() {
MessageBox.Show( “ thread start “);
}
private void DoWork() {
Thread t = new Thread( new ParameterizedThreadStart( this.DoSomething));
t.Start( “ guozhijian “);
}
private void DoSomething( object o) {
MessageBox.Show(o.ToString());
}
private void DoWork() {
ThreadPool.QueueUserWorkItem( new WaitCallback( this.DoSomething));
}
private void DoSomething( object o) {
MessageBox.Show( “ thread start “);
}
private void DoWork() {
ThreadPool.QueueUserWorkItem( new WaitCallback( this.DoSomething), “ guozhijian “);
}
private void DoSomething( object o) {
MessageBox.Show(o.ToString());
}
private void DoWork() {
string name = “ guozhijian “;
ThreadPool.QueueUserWorkItem( new WaitCallback( delegate( object o){
MessageBox.Show(name);
}));
}
private void DoWork() {
WaitCallback wc = new WaitCallback( this.DoSomething);
ThreadPool.QueueUserWorkItem(wc, “ Guozhijian “);
}
private delegate void MyInvokeDelegate( string name);
private void DoSomething( object o) {
this.Invoke( new MyInvokeDelegate( this.ChangeText), o.ToString());
}
private void ChangeText( string name) {
this.textBox1.Text = name;
}
private void DoWork() {
WaitCallback wc = new WaitCallback( this.DoSomething);
ThreadPool.QueueUserWorkItem(wc, “ Guozhijian “);
}
private void DoSomething( object o) {
this.Invoke( new Action< string>( this.ChangeText), o.ToString());
}
private void ChangeText( string name) {
this.textBox1.Text = name;
}
本例传递一个参数,System.Action有很多个重载,可以无参数(非泛型),而最多可以有四个参数,同样采用匿名方法,不使用泛型形式的System.Action,如下:
private void DoWork() {
WaitCallback wc = new WaitCallback( this.DoSomething);
ThreadPool.QueueUserWorkItem(wc, “ Guozhijian “);
}
private void DoSomething( object o) {
this.Invoke( new Action( delegate() {
this.textBox1.Text = o.ToString();
}));
}
private void DoWork() {
WaitCallback wc = new WaitCallback( this.DoSomething);
ThreadPool.QueueUserWorkItem(wc, “ Guozhijian “);
}
private void DoSomething( object o) {
System.Func< string, int> f = new Func< string, int>( this.GetId);
object result = this.Invoke(f,o.ToString());
MessageBox.Show(result.ToString());
}
private int GetId( string name) {
this.textBox1.Text = name;
if (name == “ Guozhijian “) {
return 999;
}
else {
return 0;
}
}
本文例中都是用this来引用,这里this替换为窗体任何一个控件的句柄都是OK的,因为Control.Invoke含义是将方法委托给拥有该Control的线程去执行。
很不错的文章。想当时自己学习多线程的时候绕了很久。
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/209230.html原文链接:https://javaforall.net
