When we write Remoting programs or other applications, we inevitably have to deal with threads. .Net allows us to easily create a thread, but the methods it provides for creating threads and starting threads do not provide obvious parameters. If we What should I do if I want to use a thread to start a method with parameters in a class? The following is a brief introduction on how to use the rich framework provided by .NET to implement this function. In order to introduce the whole process in vivid detail, I created the following .NET class, which is also the carrier of the thread startup method. The class looks like this:
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 "The parameter value is:"+parameter;
}
// for mutil-parameters passed
public string MyMutilParameters(string param1,string param2){
return "The connection result of parameter 1 and parameter 2 is: "+param1+param2;
}
}
}
Hehe, my English is not good. Please forgive me for the poor writing of the comments (because they are in English). I hope it does not affect your reading. I think it is necessary for me to briefly talk about the content contained in the above class. First, it contains two constructors, one with parameters and one without (this is intentionally arranged). I think you will guess it through the names of other methods in the class. I will introduce 3 methods to pass parameters, and then I will introduce them one by one. First, let's look at how to start a thread. First, we can use a function to instantiate an instance of the ThreadStart delegate, and then use this instance as the parameter new thread (Thread) object, and finally Start the thread. Want to know more Please refer to the Thread section of the MSDN documentation for more information.
In order to test our results, I created a WinForm project, which has a Form and 4 buttons. If you need all the source code, please send an email to [email protected] . I will send it to you if I have time. What follows is a detailed description of each method.
1. Use a constructor to pass parameters
. As we all know, we can use a constructor with parameters to construct an object. In this case, we can use the constructor to first pass the parameter values to be used to the internal variables in the object, and then use a parameterless constructor. Parameter method to use this parameter (pretend to be a parameter). To put it simply, declare a variable in the class specifically to save the parameters required by the function, and the function becomes a parameterless form. The biggest problem with this method is that it destroys encapsulation. Although we cannot directly access these variables, hidden dangers always exist (or it doesn't matter if it looks unpleasant). The following code snippet gives the details of how to use this method to pass parameters. This is also the Click code for one of the four buttons mentioned above (Button1). In order to have parameters to pass, I defined a variable as follows globally in WinForm:
// This is parameter's value
private string myParameter = "ParameterValuen";
The button event is as follows:
// 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();
}
As mentioned above, we use the constructor to pass parameters into the class Go, and then start a thread using the method mentioned above, we can see the execution result of MyMethod1 in the output window after running the program (you can also use a TextBox or something else to display it directly on the WinForm) :ParameterValue. Just look at the function body and you will see that the result is correct. Isn't it very simple.
2. Use ThreadPool to realize parameter transfer.
We can first look at how MSDN describes ThreadPool. Provides a pool of threads that can be used to post work items, process asynchronous I/O, wait on behalf of other threads, and process timers. View its method collection, one of which is called: QueueUserWorkItem. For detailed information about this class and this method, please refer to MSDN related help. What needs to be noted here are the parameters of the QueueUserWorkItem method. The parameter WaitCallback is a delegate type. The second parameter is the parameter required by the delegate instance (after instantiating it with a function, that is, a function), which is of object type. Please see the code below for details.
// 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);
}
Because of the two properties of QueueUserWorkItem The parameters are of object type, so we need to define two resized versions of MyMethod2 in MyClass in order to satisfy the parameters of the method. Similarly, we passed the parameter myParameter in and ran the program. When we click Button2, the result of MyMethod2 executing myParameter as a parameter will appear in the output window.
3. Next is the last method to use asynchronous delegation to realize parameter transfer
. Similarly, for detailed information about delegation, please refer to MSDN, which is very detailed above. We are going to use the BeginInvoke and EndInvoke methods here. First, we give the method of passing a parameter as follows:
// 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 ("Function call return value: {0}n", DelegateInstance.EndInvoke(result));
}
First, in order to use the delegate, we declare a delegate of MyMethod3Delegate, which specifies a parameter and return value Functions that are strings are eligible, so we define a MyMethod3 method in MyClass. The structure of this function conforms to the above delegate, so we can use this method to instantiate a delegate when Button3 is clicked, and then we call this method asynchronously. In order to get the return result, we wrote the AfterMyMothod3 method to display the function execution results. Run the program and click Button3 to see that the results output in Output are the results of MyMethod3 execution with parameters. Finally, I give a method on how to pass multiple parameters. My example is to pass 2 parameters. The code is as follows:
// 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 ("Multi-parameter function call returns result: {0}n", DelegateInstance.EndInvoke(result ));
}
Due to space constraints, the code will not be explained in detail. Please correct me if there are any inaccuracies. Thank you for reading! Contact information: [email protected] CSDN Forum ID: cuike519
Reference documents: