There are two ways to implement a thread call method with parameters.

Source: Internet
Author: User

In. NET Framework 2.0, there are two ways to implement a thread call method with parameters.

First, use parameterizedthreadstart.

When the system. Threading. thread. Start (system. Object) overload method is called, the objects containing data are passed to the thread.

Using parameterizedthreadstart is not a safe method for passing data types, because the system. Threading. thread. Start (system. Object) method overload accepts any object.

This method is not recommended, so it is not detailed here, the specific usage see: http://msdn2.microsoft.com/zh-cn/library/system.threading.parameterizedthreadstart (vs.80). aspx

Parameterizedthreadstart parstart = new parameterizedthreadstart (threadmethod );
Thread mythread = new thread (parstart );
Object o = "hello ";
Mythread. Start (O );

// Threadmethod:
Public void threadmethod (Object parobject)
{
// Program code
}

Second, 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.

The Code is as follows (this example is from msdn)

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

// 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 .");
}
}

 

========================================================== ==========================================

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:
/// <Summary>
/// Delegate function be invoked by main thread
/// </Summary>
Private void invokefun ()
{
If (maid. value <100)
Prgbar. value = prgbar. Value + 1;
}

2. subthread entry functions:
/// <Summary>
/// Thread function interface
/// </Summary>
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 the thread pool
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)
{
//....
}

 

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.