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));
}