How to pass arguments when calling a thread

Source: Internet
Author: User
Tags define constructor documentation implement net thread

We inevitably have to deal with threads when writing remoting programs or other applications. NET makes it easy to create a thread, but it provides a way to create threads and start threads without apparently providing parameters, what if we use threads to start a method with parameters in the class? Here is a simple introduction to how to use. NET provides a rich framework to implement this functionality. In order to be able to describe the whole process in vivid detail, I built one of the following. NET class, which is also the carrier of a method to start with a thread. The class is as follows:

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 is private,but it can being public or other

private void MyMethod2 (string parameter) {

Do something

Console.Write (parameter);

}

Because delegate WaitCallback ' s parameter Type is Object

I'll convert it to string.

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 The result is: "+PARAM1+PARAM2;

}

}

}

Hey, my English is not good, note writing is not easy to forgive (because the use of English), I hope it does not affect your reading. I think it is necessary for me to simply say what is contained in the class above. First, there are two constructors, one with a parameter and one without (this is intentionally arranged). Through the names of other methods in the class I think you'll guess. I'll introduce 3 ways to pass parameters, and I'll explain them each. First, let's look at how to start a thread, first we can instantiate an instance of the ThreadStart delegate with a function, and then use this instance as the parameter new thread (thread) object, and finally start the thread. For more information, refer to the Thread section of the MSDN documentation.

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 mail to wu_jian830@hotmail.com, if I have time I will send you the past. Next 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, so that we can use the constructor to pass the parameter value that we use to the internal variable inside the object, and then use a parameterless method to use this argument (pretend parameters). Simply put, declaring a variable inside a class is designed to hold the arguments that the function requires, and the function becomes a parameterless form. The biggest problem with this approach is that it destroys encapsulation, although we can't directly approach these variables but the pitfalls always exist (or they may seem unpleasant). The following snippet shows how to use this method to pass the details of the parameter, which is also the click Code of One of the 4 buttons mentioned above (Button1). In order to have the parameter to pass I have defined a variable in WinForm globally as follows:

This is parameter ' s value

private string myparameter = "parametervalue\n";

The button event looks like this:

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 to the class, and then start a thread using the method described above. We can see the results of MyMethod1 execution in the Output window after running the program (you can also use a TextBox or something to display directly on WinForm): ParameterValue. Look at the function body and know that the result is correct. is not very simple.

2, the use of threadpool to achieve the transfer of parameters

Let's first take a look at what MSDN has to say about ThreadPool, provides a pool of threads that can is used to post work items, process asynchronous I/O, WA It on behalf of the other threads, and process timers. The collection of methods to view it is called: the QueueUserWorkItem method, the class, and the details of the method refer to the MSDN help. Note Here is the parameters of the QueueUserWorkItem method, parameter WaitCallback is a delegate type, the second parameter is the delegate instance (after the function instantiation, that is, a function) required by the parameter, is type object. For more information, see the code below.

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

}

Since the two parameters of QueueUserWorkItem are of type object, we have to define two MyMethod2 in MyClass to satisfy the parameters of the method. Also we pass the parameter Myparameter in, run the program, when we click the Button2 in the Output window will appear MyMethod2 will myparameter as the parameters of the implementation of the results displayed.

3, Next is the last method to implement parameter passing using asynchronous delegates

Again, the details about the delegate can be referenced in MSDN, which is very detailed. We're going to use the BeginInvoke and EndInvoke methods here. First we give a way to pass 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 mymethod3delegate delegate that states that a function of a parameter and the return value of string is eligible, so we define a MyMethod3 method in MyClass. The form of the function conforms to the above delegate, so we can instantiate a delegate using this method when Button3 clicks, and then we invoke this method in an asynchronous way, and we write a AfterMyMothod3 method to show the result of the function in order to get the return result. Run the program click Button3 you can see output of the result is MyMethod3 with parameters. Finally, I give a method of how to pass multiple parameters, my example is passing 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 ("Multiple parameter function call returns results: {0}\n", delegateinstance.endinvoke (result));

}

Because the length of the relationship code is not explained in detail. Please correct me if there is a wrong place, thank you for reading! Contact:wu_jian830@hotmail.com csdn Forum id:cuike519

Reference Documentation:

Http://www.codeproject.com/Purgatory/ThreadsinC_.asp

Http://www.msdn.com



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.