Streamline thread, delegate, and synchronization Technologies

Source: Internet
Author: User

Multi-thread implementation

1Multi-thread implementation

(1): asynchronous Delegation(In essence, Microsoft will create a thread to execute tasks and use a thread pool to complete asynchronous tasks.) There are about three technologies for implementing asynchronous delegation: voting, waiting handle, and asynchronous callback.

1. Vote:

Public delegate int TakesAWhileDelege (intms );


Static void Main (string [] args)


{


TakesAWhileDelegedl = TakesAWhile;


IAsyncResultar = dl. BeginInvoke (1000, null, null );


While (ar. IsCompleted)


Console. WriteLine ("delegate execution completed ");


}


Public static intTakesAWhile (int MS)


{


Thread. Sleep (50 );


Returnms;


}


2. Waiting handle (use AsyncWaitHandle to obtain the waiting handle WaitHandle of the delegate, and use the WaitOne method to block the current thread for 50 milliseconds, if the delegate is not completed after 50 milliseconds, false is returned)

Public delegate int TakesAWhileDelege (intms );


Static void Main (string [] args)


{


TakesAWhileDelegedl = TakesAWhile;


IAsyncResultar = dl. BeginInvoke (1000, null, null );


While (true)


{


If (ar. AsyncWaitHandle. WaitOne (50, false ))


Break;


}


Intresult = dl. EndInvoke (ar );


}


Public static intTakesAWhile (int MS)


{


Thread. Sleep (50 );


Returnms;


}


3. asynchronous callback (t passes the last two parameters of BeginInvoke, one is the callback function and the other is)


Public delegate int TakesAWhileDelege (int MS );


Static void Main (string [] args)


{


TakesAWhileDelegedl = TakesAWhile;


Dl. begininvoke( 1000, completeTake, dl );


Console. WriteLine ("adfa ");




}


Public static voidcompleteTake (IAsyncResult ar)


{




// If the dl in dl. BeginInvoke (1000, completeTake, dl); is any parameter such as 2000, the result obtained here is


// Int num = (int) ar. AsyncState;

TakesAWhileDelege dlTemp = ar. AsyncState as TakesAWhileDelege;


Intresult = dlTemp. EndInvoke (ar );


}


Public static intTakesAWhile (int MS)


{


Thread. Sleep (50 );


Returnms;


}




(2): UseThreadClass creation thread(There are no parameters and parameters. Another way to pass parameters is to build a class object. The parameter acts as a member of the class object, and then defines a threadClass3 method, it is used to pass in Thread thread2 = new Thread (threadClass3) when constructing a Thread object ))

First, I declare that the threads declared using the Thread class are all foreground threads by default, that is, will the process be terminated if one of the foreground threads is not completed after the main function is executed in time, unless you change IsBackground to true, the main thread ends and the background thread ends after the change, whether or not the execution is complete.

1. Common Parameters and no parameters

Static void Main (string [] args)


{


Threadthread1 = new Thread (threadClass1) {Name = "11", IsBackground = false };


Thread1.Start ();


Threadthread2 = new Thread (threadClass2) {IsBackground = true };


Thread2.Start (100 );


}


Static void threadClass1 ()


{


}


Static void threadClass2 (objectnum)


{


Intnums = (int) num;


}


2. Build a Class Object

Public class Mythread

{


Private int num;

Public void Mythread (int num)

{


This. num = num;

}


Public void threadClass3 ()


{


// Xxxxxxxxxxxxxxxxxxxxx


}

}

When calling a thread,

Mythread my1 = new Mythread (100 );

Thread th1 = new Thread (my1.threadClass3 );


3. thread1.Join ();

Join: it is a value blocking the thread1 process. It continues to run after the process is completed.

Thread1.Abort ();

Abort: indicates the end thread.


(3): Thread Pool(The thread in the thread pool must be a background thread. The process in the thread pool can only be used for tasks with shorter time periods. It is best to create a new thread for long threads)

1. No Parameters

Static void Main (string [] args)


{


For (int I = 0; I <= 5; I ++)


ThreadPool. QueueUserWorkItem (threadClass );


Console. ReadLine ();


}


Static void threadClass (objectnum)


{


Thread. Sleep (3000 );


Console. WriteLine (Thread. CurrentThread. ManagedThreadId );


}

2. Parameters

Construct a class with parameters as members of the class

Public class MythreadA


{


Private int num = 100;


Public MythreadA (intnumS)


{


This. num = numS;


}


Public void threadClass3 (object N)


{


Thread. Sleep (3000 );


Console. WriteLine (Thread. CurrentThread. ManagedThreadId + ":" + num );


}


}

Thread Pool


Static void Main (string [] args)


{


For (int I = 0; I <= 5; I ++)


{


MythreadA Mythread1 = newMythreadA (100 + I );


// QueueUserWorkItem requires a WaitCallback delegate as a parameter, which requires an object type parameter. If we need to pass parameters, we can create a new class ..


ThreadPool. QueueUserWorkItem (Mythread1.threadClass3 );




}


Console. ReadLine ();


}




2. synchronous implementation

All of the above are asynchronous implementations. In fact, sometimes we need to share files or data with different threads. This requires that only one thread can access and change the sharing status at a time, so we need to use the synchronization technology.

Multithreading synchronization technologies include:

Lock,Monitor(LockResolved by the compilerMonitor),Mutex,Semaphore


For example, for the same object20Processes are passed over the object.NumLoop5000Secondary Addition1Operation, the problem occurs at this time when the first threadIEqual2000, Judge<5000When you can enter the loop body, the thread suddenly gives the second thread, and the second thread continues to execute it inI = 1The operation is paused.ISuddenly becomes2000, Equivalent to less1999.. If this happens frequently20The total number of threads Must be smaller10000.


Lock(Locked)

Private object o = new object

For (int I = 0; I <5000; I ++)

{

Lock (object)

{

Num ++;

}

}

Monitor

Private object o = new object


LockResolved by the compilerMonitor,MonitorCallEnter(Object) Method to keep the thread waiting until the current thread is locked by the object before it starts to operate. Of course, whether it is running or triggering an exception, we must callExit(Object) Method, of courseMonitorBetterLockIt can be set to wait for the lock time, that isTryEnterMethod

For example,Set to let the thread wait500Millisecond. If other threads are locked, the system returnsLockifIsFalse,

Bool lockif = false;

Monitor. TryEnter (object, 500, ref lockif );

If (lockif)


{

//Perform operations

}


Mutex (Mutual Exclusion),Mutual Exclusion WaitHandle (WaitHandle was mentioned during asynchronous delegation)

Mutex is similar to Monitor. It also ensures that only one process is mutex-locked. The difference is that mutex can be crossed.


Multiple processes (not threads) are mutually exclusive for synchronization. For example, if an application can only start one, the effect must be named mutex. If you want to achieve this, the non-naming mutex cannot cross-process.


Mutex mymutex = new Mutex (false, "myMutex", outmutexif );


If (! Mutexif)


{


// Execute the code


}


Or ******************************


If (mymutex. WaitOne (50 ))


{


// Terminate the thread for 50 milliseconds until the thread has completed the operation


// Execute the code


}


Semaphore (Semaphores),Also inheritWaitHandle

Semaphores are similar to Mutex, which is a type of Mutex lock that controls the number of threads. First

Define a semaphore first

Var semaphore = new SemaphoreSlim (4, 4 );

Then, the system traverses 20 processes and transmits semaphore as a parameter to each process execution method.

SemaphoreSlim semaphore = o as SemaphoreSlim;


BoolisCompleted = false;


While (! IsCompleted)

{


// Stop the current process until it can enter the semaphore.

If (semaphore.. Wait (600 ))

{

Try


{




} Finally


{


Semaphore. Release (); // Release a semaphore. You can also specify several semaphore parameters to Release.


IsCompleted = true;


}


} Else


{


// When the four semaphores are full, the thread continues to wait.


}


}














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.