We will inevitably deal with threads when writing a Remoting program or some other applications. .NET makes us easy to create a thread, but it provides the creative thread and the starting thread does not provide a clearly providing parameters, if we What should I do if I use the thread to start a class with parameters in the class? The following is a simple introduction to how to use the rich framework provided by .NET to implement this function. In order to vividly introduce the entire process, I establish a .NET class below, which is also a carrier for the method of starting with a thread. The class is as follows:
Using system;
Namespace WindowsApplication1
{
///
/// Summary Description for Urlfetcher.
/// summary>
Public class myclass {
// for normal 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 convetring.
Public void mymethod2 (Object parameter) {
This.mymethod2 (String) Parameter;
}
// for method 3
Public string mymethod3 (String parameter) {
Return "parameter value is:" parameter;
}
// for MUTIL-Parameters Passed
Public String MymutilParameters (String Param1, String Param2) {
Return "parameter 1 and parameter 2 connection results are:" param1 param2;
}
}
}
Hey, my English is not working, the note is not good, please forgive (because English), I hope that you have no reading. I think I need to simply talk about the content contained in this class. First include two constructor, a band with parameters without (here, it is intentional). Through the name of other methods in the class, I think you must guess that I will introduce three ways to deliver parameters, and I will introduce one by one. First we see how to start a thread, first we can use a function to instantiate the ThreadStart entrusted by the ThreadStart, and then use this instance as a parameter NEW thread (Thread) object, finally put this thread start, want to know more Please refer to the three part of the MSDN document.
In order to test our results, I built a WinForm project, which has a Form and 4 buttons. If you need all the source code, please send an email to wu_jian830@hotmail.com, if I have time, I will send you it. Next is a detailed description of each method. 1. Use constructor to pass parameters
It is well known that we can use a parameter constructor to construct an object, which we can use the constructor to pass the parameter value to be used to the internal variable in the object, and then use this parameter using this parameter ( Pretending parameters). Simply put, in the class, a variable is specifically used to save the parameters required to save functions, the function becomes uncommon-free form. The biggest problem with this approach is to destroy the encapsulation, although I can do these variables directly, but I always exist (or you can see it). The following code snippet gives how to use this method to pass the details of the parameters, which is also a click code of a button (Button1) in the four buttons mentioned above. In order to have parameters, I define a variable in WinForm:
// this is parameter's value
Private string myparameter = "parameterValue / n";
The button event is as follows:
// passed parameters to three by construct
Private void button1_click (Object sender, system.eventargs e) {
Myclass instance = new myclass (myparameter);
New Threadstart (Instance.Mymethod1)). Start ();
}
As mentioned above, we use the constructor to pass the parameters to the class, then start a thread in using the method mentioned above, we can see the execution result of MyMethod1 in the Output window after running the program (you You can also use a TextBox or something else to display directly on WinForm): ParameterValue. Look at the function body knows the result is correct. Is not it simple.
2, use threadpool to implement the passage of parameters
Let's take a look at how MSDN describes threadpool, provides a pool of threads That Can Be buy to post Work Items, Process Asynchronous I / O, Wait on Behalf of Other Threads, and Process Timers. View it There is a method called: QueueUserWorkItem, please refer to MSDN-related help for details. Here, it is necessary to pay attention to the parameters of the QueueUserWorkItem method. The parameter waitcallback is a delegate type. The second parameter is the parameter required for the entrustment instance (after instantification, it is a function), which is Object type. See the code below for details.
// Passed Parameter to Thread by ThreadPool
Private void button2_click (object sender, system.eventargs e) {
Myclass installation = new myclass ();
ThreadPool.QueueUserWorkItem (New WaitCallback (Instancet.Mymethod2), MyParameter
}
Since the two parameters of QueueUserWorkItem are Object Types So we want to define two MYMETHOD2 re-documented versions in MyClass, and the purpose is to meet the parameters of the method. Similarly, we pass the parameters myparameter, run the program. When we click on Button2, the MYMETHOD2 will appear in the Output window to display myParameter as the result of the parameter. 3, next is the last method to use asynchronous commission to implement the passage of parameters
Similarly, detailed information about the commission can be referred to MSDN, which is very detailed above. We should use the BeginInvoke and EndInvoke methods here. First we give the way to deliver a parameter as follows:
// passed Parameter by Asynchronous Delegate
Delegate string mymethod3delegate (String parameter);
Private void Button3_Click (Object Sender, System.Eventargs E) {
Myclass installation = new myclass ();
Mymethod3delegate mymethod3 = new mymethod3dlegate (instance.mymethod3);
Mymethod3.beginInvoke ("ParameterValue", New AsyncCallback (instermothod3), null;
}
Public void aftermothod3 (IASYNCRESULT RESULT) {
AsyncResult async = (askNCRESULT) RESULT
Mymethod3delegate delegateInstance = (mymethod3dlegate) 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, the entrustment describes the function of a parameter and the return value for string, so we define a MYMETHOD3 method in MyClass. The function of this function meets the above delegation, so we can instantiate a delegate with this method when you click on Button3, then we call this method asynchronously. In order to get the return result, we write the AftermothoD3 method to display the function. Execution results. The run program Click on Button3 to see the result of output in Output as the result of the MYMETHOD3 with parameters. Finally, I give a method of transmitting multiple parameters, my example is to pass two parameters. code show as below:
// MUTIL-Parameters Passed
Delegate String MymutilParamsdelegate (String Parameter1, String Parameter2);
Private void button4_click (object sender, system.eventargs e) {
Myclass installation = new myclass ();
MymutilParamsdelegate Mutilparams = New MymutilParamsdeLegate (Instance.MYMUTILPARETERES);
Mutilparams.BeginInvoke ("Param1", "Params2", New AsyncCallback (Aftermutilparams), NULL);
}
Public void aftermutilparams (isyncResult results) {asyncResult async = (asyncRESult) Result
Mymutilparamsdelegate delegateInstance = (mymutilparamsdelegate) async.asyncdelegate;
Console.writeline ("Multi-Parameter Function Call Return Result: {0} / N", delegateInstance.endinvoke (Result);
}
Since the space relationship code is not described in detail. If you have an incorrect place, please refer to you, thank you! Contact: wu_jian830@hotmail.com 9cbs forum ID: cuike519
Reference documentation:
Http://www.codeproject.com/purgatory/threadsinc_.asp
http://www.msdn.com