扫一扫
分享文章到微信
扫一扫
关注官方公众号
至顶头条
using System; namespace WindowsApplication1 { /// <summary> /// Summary description for UrlFetcher. /// </summary> 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)); } |
// mutil-parameters passed delegate string MyMutilParamsDelegate(string parameter1,string parameter2); private void button4_Click(object sender, System.EventArgs e) { MyClass instance = new MyClass(); MyMutilParamsDelegate mutilParams = new MyMutilParamsDelegate(instance.MyMutilParameters); mutilParams.BeginInvoke("param1","params2",new AsyncCallback(AfterMutilParams),null); } public void AfterMutilParams(IAsyncResult result){ AsyncResult async = (AsyncResult) result; MyMutilParamsDelegate DelegateInstance = (MyMutilParamsDelegate) async.AsyncDelegate; Console.WriteLine ("多参数函数调用返回结果:{0}\n", DelegateInstance.EndInvoke(result)); } |
如果您非常迫切的想了解IT领域最新产品与技术信息,那么订阅至顶网技术邮件将是您的最佳途径之一。
现场直击|2021世界人工智能大会
直击5G创新地带,就在2021MWC上海
5G已至 转型当时——服务提供商如何把握转型的绝佳时机
寻找自己的Flag
华为开发者大会2020(Cloud)- 科技行者