Visual C # multi-thread parameter passing Analysis

Source: Internet
Author: User

 

When writing remoting programs or other applications, we will inevitably deal with threads ,. net makes it easy to create a thread, but the method provided by it to create a thread and start a thread does not provide obvious parameters, what if we want to use a thread to start a method with parameters in the class? The following describes how to use the rich framework provided by. Net to implement this function. To give a vivid and detailed introduction to the entire process, I established the following. Net class, which is also the carrier of the method to start with a thread. Class:

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 value:" + parameter;

}

 

// For mutil-parameters passed

Public String mymutilparameters (string param1, string
Param2 ){

Return "result of connection between parameter 1 and parameter 2:" + param1 + param2;

}

 

}

}

 

Hey, I am not good at English. Please forgive me for writing comments badly (because I use English). I hope your reading will not be affected. I think it is necessary for me to briefly discuss the content contained in the above class. First, it contains two constructor functions, one without parameters (which is intentionally arranged here ). By using the names of other methods in the class, I guess I will introduce three methods to pass parameters. Next 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 entrusted by threadstart, and then use this instance as the parameter new thread (thread) object, finally, start the thread. For more information, see the thread section in the msdn document.

To test our results, I created a winform project with a form and four buttons. If I have time, I will send it to you. The following is a detailed description of each method.

1. Use constructors 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 the internal variables in the object, then you can use this parameter (pretend parameter) by using a non-parameter method ). Simply put, declare a variable in the class to save the parameters required by the function, and the function becomes a form without parameters. The biggest problem with this method is the destruction of encapsulation. Although we cannot directly approach these variables, the hidden risks always exist (or it may seem uncomfortable ). The following code snippet shows how to use this method to pass the details of parameters. This is also the click code of a button (button1) in the four buttons mentioned above. To have parameters that can be passed in, I defined the following global variable in winform:

// This is parameter's Value

Private string myparameter = "parametervalue/N ";

The button event is as follows:

// Passed parameters to thread by construct

Private void button#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 to the class, and then start a thread using the method described above, the execution result of mymethod1 is displayed in the output window after the program is run (you can also use a textbox or something to directly display it on winform): parametervalue
. Check the function body to see that the result is correct. Is it easy.

2. Use threadpool to transmit Parameters

First, let's take a look at how msdn describes threadpool. Provides a pool of threads that can be used
Post work items, process asynchronous I/O, wait on behalf of other threads, and
Process timers. view its method set. One of them is queueuserworkitem.
For more information, see the msdn help. Note that the parameter of the queueuserworkitem method is used. The waitcallback parameter is a delegate type, and the second parameter is the parameter required by the delegate instance (after the function is instantiated, it is also a function, is of the object type. For details, see the following code.

// 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 the two parameters of queueuserworkitem are of the object type, we need to define two duplicate versions of mymethod2 in myclass to satisfy the parameters of this method. Similarly, we passed the myparameter parameter to run the program. When we click button2, mymethod2 will appear in the output window and display the myparameter as the result of parameter execution.

3. Next, the last method uses asynchronous delegation to transmit parameters.


For more information about delegation, see msdn. Here we will use the begininvoke and endinvoke methods. First, the method for passing a parameter is 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, we declared a mymethod3delegate delegate to use the delegate. This delegate indicates that a function with a parameter and a return value of string meets the condition, so we defined a mymethod3 method in myclass. The struct of this function conforms to the preceding delegate, so we can use this method to instantiate a delegate when button3 clicks, and then call this method asynchronously, to get the returned result, we wrote the aftermymothod3 method to display the execution result of the function. Run the program and click button3. The output result in output is the result of mymethod3 parameter execution. Finally, I will show how to pass multiple parameters. In my example, two parameters are passed. 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 return result: {0}/N ",
Delegateinstance. endinvoke (result ));

}

Because the space link code is not described in detail. Please correct me if there are any errors. Thank you for reading!

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.