分类:
2008-10-15 13:53:32
using System; namespace WindowSAPplication1 { /// /// Summary description for UrlFetcher. /// public class MyClass{ // for method 1 private string _parameter; public MyClass(string parameter){ this._parameter = parameter; } public void MyMethod1(){ if(this._parameter!=null){ // do something Console.Write(this._parameter); } } // for method 2 public MyClass(){} // this method is private,But it can be public or other private void MyMethod2(string parameter){ // do something Console.Write(parameter); } // Because delegate WaitCallback's parameter Type is object // I will convert it to string. public void MyMethod2(object parameter){ this.MyMethod2((string)parameter); } // for method 3 public string MyMethod3(string parameter){ return "参数值为:"+parameter; } // for mutil-parameters passed public string MyMutilParameters(string param1,string param2){ return "参数1和参数2连接结果为:"+param1+param2; } } } |
// This is parameter's value private string myParameter = "ParameterValue\n"; |
// passed parameters to thread by construct private void button1_Click(object sender, System.EventArgs e) { MyClass instance = new MyClass(myParameter); new Thread (new ThreadStart(instance.MyMethod1)).Start(); } |
// passed parameter to thread by ThreadPool private void button2_Click(object sender, System.EventArgs e) { MyClass instance = new MyClass(); ThreadPool.QueueUserWorkItem (new WaitCallback (instance.MyMethod2),myParameter); } |
// passed parameter by asynchronous delegate delegate string MyMethod3Delegate(string parameter); private void button3_Click(object sender, System.EventArgs e) { MyClass instance = new MyClass(); MyMethod3Delegate myMethod3 = new MyMethod3Delegate(instance.MyMethod3); myMethod3.BeginInvoke("parameterValue",new AsyncCallback(AfterMyMothod3),null); } public void AfterMyMothod3(IAsyncResult result){ AsyncResult async = (AsyncResult) result; MyMethod3Delegate DelegateInstance = (MyMethod3Delegate) async.AsyncDelegate; Console.WriteLine ("函数调用返回值:{0}\n", DelegateInstance.EndInvoke(result)); } |
首先为了使用委托我们声明了一个MyMethod3Delegate的委托,该委托说明一个参数和返回值为string的函数是符合条件的,所以我们在MyClass里面定义了一个MyMethod3的方法。该函数的型构符合上面的委托,所以我们可以在Button3点击的时候用这个方法实例化一个委托,然后我们使用异步的方式调用这个方法,为了得到返回结果我们写了AfterMyMothod3方法用来显示该函数的执行结果。运行程序点击Button3可以看到Output中输出的结果为MyMethod3带参数执行的结果。最后我给出如何传递多个参数的方法,我的例子是传递2个参数。代码如下:
[1]