C # multi-thread parameter passing

Source: Internet
Author: User

In a multi-threaded or single-threaded task, it is always troublesome to include input parameters in the thread. A common method is to pass parameters using class and object variables, this method is easy to understand, but it is very troublesome to use in some occasions. We will not introduce it here. We will mainly introduce one. the newly added method with a parameter running thread in NET2.0. The example program is as follows:

ParameterizedThreadStart ParStart = new ParameterizedThreadStart (ThreadMethod );
Thread myThread = new Thread (ParStart );
Object o = "hello ";
MyThread. Start (o );

ThreadMethod:
Public void ThreadMethod (object ParObject)
{
// Program code
}

If there are multiple parameters, You can bind the object to an array or a dynamic list, and then unpack it when using it.

Is this much simpler ,,,
----------------------------
[Conversion] I personally think that it is easy to create a separate class for the thread and assign values to the variables in the class initialization function to pass in parameters. Some of the methods below are problematic, but I am too lazy to make the mistake when I have achieved the goal. Which of the following friends has noticed the problem and reminded me. Haha...

Method 1:
In VS2003, access is not allowed. See
Generally, exceptions occur when you operate controls on the form directly in the Child thread. This is because the child thread and the thread running the form are different spaces, therefore, to operate controls on forms in subthreads, it is impossible to simply operate through the control object name, but it does not mean that operations cannot be performed. Microsoft provides the Invoke method, its role is to let the subthread tell the form thread to complete corresponding control operations.

Now we use a thread-controlled process bar to describe the following steps:

1. Create the Invoke function, which is roughly as follows:
///
/// Delegate function be invoked by main thread
///

Private void InvokeFun ()
{
If (maid. Value <100)
PrgBar. Value = prgBar. Value + 1;
}

2. subthread entry functions:
///
/// Thread function interface
///

Private void ThreadFun ()
{
// Create invoke method by specific function
MethodInvoker mi = new MethodInvoker (this. InvokeFun );

For (int I = 0; I <100; I ++)
{
This. BeginInvoke (mi );
Thread. Sleep (100 );
}
}

3. Create a subthread:
Thread thdProcess = new Thread (new ThreadStart (ThreadFun ));
ThdProcess. Start ();

Note:
Using System. Threading;
Private System. Windows. Forms. ProgressBar prgBar;

Method 2:
Control. checkforillegalcrossthreadcils = False cancels the thread security protection mode!

Method 3: With Parameters
Parameters can be passed to the thread using methods or attributes of classes:
Public class UrlDownloader
{
String url;

Public UrlDownloader (string url)
{
This. url = url;
}

Public void Download ()
{
WebClient wc = new WebClient ();
Console. WriteLine ("Downloading" + url );
Byte [] buffer = wc. DownloadData (url );
String download = Encoding. ASCII. GetString (buffer );
Console. WriteLine (download );
Console. WriteLine ("Download successful .");

// Here you can save and process the download ......
}
}

[... Use them in another class...]

UrlDownloader downloader = new UrlDownloader (yourUrl );
New Thread (new ThreadStart (downloader. Download). Start ();

Note how parameters are passed.

Method 4: With Parameters
ThreadStart starter = delegate {Download (yourUrl );};
New Thread (starter). Start ();

// Use thread
WaitCallback callback = delegate (object state) {Download (string) state );};
ThreadPool. QueueUserWorkItem (callback, yourUrl );

Method 5: With Parameters
Thread t = new Thread (new ParameterizedThreadStart (DownloadUrl ));
T. Start (myUrl );
Static void DownloadUrl (object url)
{
//....
}
--------------------------

--------------------------
C # The thread calls a method with Parameters
I used a small application using the c # language. In the process of doing this, I encountered a difficulty. It is better to call a thread with parameters. After searching online materials, found a simple solution.
In our previous studies, we often encountered threads without parameters. Therefore, when a thread must use parameters, we were at a loss, now we use this method to solve the problem. The actual principle is: encapsulate the methods and parameters of thread execution into a class. By instantiating this class, the method can call attributes to implement indirect type-safe parameter passing. See the following code:

Using System;
Using System. Threading;

// The ThreadWithState class contains the task to be executed and the method to execute the task.
Public class ThreadWithState {
// The attribute to be used, that is, the parameter to be passed
Private string boilerplate;
Private int value;

// Constructor Containing Parameters
Public ThreadWithState (string text, int number)
{
Boilerplate = text;
Value = number;
}

// Method to be thrown to the thread for execution. There is no return type in this place to allow ThreadStart to call
Public void ThreadProc ()
{
// Here is the task to be executed. Only the input parameters are displayed.
Console. WriteLine (boilerplate, value );
}
}
--------------- Separation line ---------------
// The class used to call the above method is the entry for execution in this example.
Public class Example {
Public static void Main ()
{
// Instantiate the ThreadWithState class to provide parameters for the thread
ThreadWithState tws = new ThreadWithState (
"This report displays the number {0}.", 42 );

// Create the thread for executing the task and execute
Thread t = new Thread (new ThreadStart (tws. ThreadProc ));
T. Start ();
Console. WriteLine ("Main thread does some work, then waits .");
T. Join ();
Console. WriteLine (
"Independent task has completed; main thread ends .");
}
}
From the above example, we can get the desired result clearly. Pay attention to the usage of this Code:
Thread t = new Thread (new ThreadStart (tws. ThreadProc ));

 


From Darren

Related Article

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.