C # series of methods for passing parameters by thread) -- continue to search engine research

Source: Internet
Author: User

We are writing remoting.ProgramOr some other applications may have to 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:

 

Code
Using System;

NamespaceWindowsapplication1

{

/// <Summary>

///Summary Description for urlfetcher.

/// </Summary>

Public ClassMyclass {

//For method 1

Private String_ Parameter;

PublicMyclass (StringParameter ){

This. _ Parameter=Parameter;

}

Public VoidMymethod1 (){

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 VoidMymethod2 (ObjectParameter ){

This. Mymethod2 ((String) Parameter );

}

 

//For method 3

Public StringMymethod3 (StringParameter ){

Return "The parameter value is:"+Parameter;

}

 

// for mutil-parameters passed

Public string mymutilparameters ( string param1, string param2) {

Return "The connection result between parameter 1 and parameter 2 is:"+Param1+Param2;

}

}

}

 

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.

1. Use constructors to PASS Parameters

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 ). BelowCodeThe snippet shows how to use this method to pass the details of the parameter, which 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:

 

Code
// This is parameter's Value

Private   String Myparameter =   " Parametervalue \ n " ;

//The button event is as follows:

//Passed parameters to thread by construct

Private VoidButton#click (ObjectSender, system. eventargs e ){

Myclass instance= NewMyclass (myparameter );

NewThread (NewThreadstart (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 to post work items, process asynchronous I/O, wait on behalf of other threads, and process timers. one of the methods is queueuserworkitem. For details about this class and the method, 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.

 

Code
// Passed parameter to thread by threadpool

Private   Void Button2_click ( Object Sender, system. eventargs e ){

Myclass instance= NewMyclass ();

Threadpool. queueuserworkitem (NewWaitcallback (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:

 

Code
// Passed parameter by asynchronous delegate

Delegate   String Mymethod3delegate ( String Parameter );

Private VoidButton3_click (ObjectSender, system. eventargs e ){

Myclass instance= NewMyclass ();

Mymethod3delegate mymethod3= NewMymethod3delegate (instance. mymethod3 );

Mymethod3.begininvoke ("Parametervalue",NewAsynccallback (aftermymothod3 ),Null);

}

Public VoidAftermymothod3 (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:

 

Code
// Mutil-parameters passed

Delegate   String Mymutilparamsdelegate ( String Parameter1, String Parameter2 );

Private VoidButton4_click (ObjectSender, system. eventargs e ){

Myclass instance= NewMyclass ();

Mymutilparamsdelegate mutilparams= NewMymutilparamsdelegate (instance. mymutilparameters );

Mutilparams. begininvoke ("Param1","Params2",NewAsynccallback (aftermutilparams ),Null);

}

 

Public VoidAftermutilparams (iasyncresult result ){

Asyncresult async=(Asyncresult) result;

Mymutilparamsdelegate delegateinstance=(Mymutilparamsdelegate) async. asyncdelegate;

Console. writeline ("Multi-parameter function call return result: {0} \ n", Delegateinstance. endinvoke (result ));

}

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.