Thread usage knowledge

Source: Internet
Author: User

1. Basic steps:

1. Create a method as the thread entry point;
2. Create a threadstart or parameterizedthreadstart delegate and pass the address of the method defined in the previous step to the Delegate constructor;
3. Create a thread object and use threadstart or parameterizedthreadstart as the constructor parameter;
4. Create features (names and priorities) for any initialization thread ),
5. Call the thread. start method. The delegate method established in step 1 is executed as soon as possible.

 

2. Example of using ParameterizedThreadStart multi-thread delegation (console Program)

Using System;
Using System. Collections. Generic;
Using System. Text;
Using System. Threading;

 

Namespace AddWithThreads
{
# Region Helper class
Class AddParams
{
Public int a, B;

Public AddParams (int numb1, int numb2)
{
A = numb1;
B = numb2;
}
}
# Endregion

Class Program
{
Static void Main (string [] args)
{
Console. WriteLine ("****** Adding with Thread objects *****");
Console. WriteLine ("ID of thread in Main (): {0 }",
Thread. CurrentThread. ManagedThreadId );

AddParams ap = new AddParams (10, 10 );
Thread t = new Thread (new ParameterizedThreadStart (Add ));
T. Start (ap );
Console. ReadLine ();
}

# Region Add method
Static void Add (object data)
{
If (data is AddParams)
{
Console. WriteLine ("ID of thread in Main (): {0 }",
Thread. CurrentThread. ManagedThreadId );

AddParams ap = (AddParams) data;
Console. WriteLine ("{0} + {1} is {2 }",
Ap. a, ap. B, ap. a + ap. B );
}
}
# Endregion
}
}

3. An example of thread synchronization using the lock flag lock (console Program)

 
Private object threadlock = new object (); -- 1 defines the lock flag
Public void PrintNumbers ()
{
Lock (threadLock) -- 2 use the lock flag
{

Console. WriteLine ("-> {0} is executing PrintNumbers ()",
Thread. CurrentThread. Name );

 

Console. Write ("Your numbers :");
For (int I = 0; I <10; I ++)
{
Random r = new Random ();
Thread. Sleep (100 * r. Next (5 ));
Console. Write ("{0},", I );
}
Console. WriteLine ();
}
}
The above method ensures that once a thread enters the lock range, other threads cannot access the lock mark before it exits the lock range and releases the lock, so that the logic is not interrupted.

 

4. An example of using [Synchronization] for thread Synchronization (console Program)

Using System. Runtime. Remoting. Contexts; -- 1 introduce the Command Space
[Synchronization] -- 2 All printer methods are thread-safe
Public class Printer: ContextBoundObject-3 ContextBoundObject defines the base class of all context-bound classes
{


Public void PrintNumbers ()
{

// Display Thread info.
Console. WriteLine ("-> {0} is executing PrintNumbers ()",
Thread. CurrentThread. Name );

 

// Print out numbers.
Console. Write ("Your numbers :");
For (int I = 0; I <10; I ++)
{
Random r = new Random ();
Thread. Sleep (100 * r. Next (5 ));
Console. Write ("{0},", I );
}
Console. WriteLine ();

}
}

5. Example of using timer callback programming (console Program)

Using System;
Using System. Collections. Generic;
Using System. Text;
Using System. Threading;

 

Namespace TimerApp
{
Class Program
{
Static void Main (string [] args)
{
Console. WriteLine ("****** Working with Timer type ****** \ n ");

// Create a Callback delegate.
TimerCallback timeCB = new TimerCallback (PrintTime );

// Set the timer class
Timer t = new Timer (
TimeCB, // TimerCallback delegate type
"Hello From Main", // Any info to pass into the called method (null for no info ).
0, // the waiting time before the start
1000); // The interval of each call (in milliseconds)

Console. WriteLine ("Hit key to terminate ...");
Console. ReadLine ();
}

 

Static void PrintTime (object state)
{
Console. WriteLine ("Time is: {0}, Param is: {1 }",
DateTime. Now. ToLongTimeString (), state. ToString ());
}
}
}

 

6. Use the BackgroundWorker component

1. Add a BackgroundWorker
2. The control has two events:
The Dowork handler indicates the method called by the backgroundworker during the next thread execution.
And RunWorkComplete handler indicates the method that will be called after BackgroundWorker completes operations in the background

3. Calling the RunWorkerAsync method of BackgroundWorker will cause a Dowork event.

 

7. How to Use the thread pool: (for the winform program, add textbox1 first)

Private void DoWork (){
WaitCallback wc = new WaitCallback (this. DoSomething );
ThreadPool. QueueUserWorkItem (wc, "Guozhijian"); // The thread pool is used here.
}

 

Private delegate void MyInvokeDelegate (string name );
Private void DoSomething (object o ){
This. Invoke (new MyInvokeDelegate (this. ChangeText), o. ToString ());
}

Private void ChangeText (string name ){
This. textBox1.Text = name;
}

 

 

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.