Multi-threaded Learning (i)

Source: Internet
Author: User
Tags throw exception

One, the reason for using threads

1. You can use threads to isolate code from other code to improve application reliability.

2. You can use threads to simplify coding.

3. Threads can be used to implement concurrent execution.

II. Basic Knowledge

1, process and thread: The process acts as the basic unit of the Operating system execution program, owns the resources of the application, the process contains the threads, the resources of the process are shared by the threads, and the threads do not own the resources.

2. Foreground thread and background thread: New line Cheng is considered foreground thread through the thread class. When all foreground threads are closed, all background threads are also terminated directly, without throwing an exception.

3, Suspend (Suspend) and Wake (Resume): Because the execution order of the thread and the execution of the program is unpredictable, so use suspend and wake prone to deadlock situations, in the actual application should be used sparingly.

4. Blocking thread: Join, blocks the calling thread until the thread terminates.

5. Terminating thread: Abort: Throws the ThreadAbortException exception to terminate the thread, and the terminated thread cannot wake. Interrupt: Throws the threadinterruptexception exception to let the thread terminate, can continue execution by catching the exception.

6, Thread priority: AboveNormal BelowNormal highest Lowest normal, default to normal.

Third, the use of threads

Thread functions can be passed through a delegate, without parameters, or with parameters (only one parameter), and can encapsulate parameters with a class or struct body.

Iv. thread Pool

Because of the cost of creating and destroying threads, excessive use of threads can cause memory resources to be wasted, and the concept of a thread pool is introduced for performance reasons.

The thread pool maintains a request queue, the thread pool's code extracts the task from the queue, and then it is delegated to a thread pool for execution, and the threads are not destroyed immediately after execution, so that tasks can be performed in the background and the overhead of thread creation and destruction can be reduced.

Thread pool thread Cheng is considered a background thread (IsBackground).

Using system;using system.collections.generic;using system.linq;using system.text;using System.Threading;using        System.threading.tasks;namespace consoleapplication1{class Program {static void Main (string[] args)            {//parameterless thread T1 = new Thread (new ThreadStart (GetName1)); T1.            IsBackground = true; T1.            Start ();            Multiple parameters, using the class internal invocation, multiple parameters can also use the struct structure UserInfo UserInfo = new UserInfo () {Name = "Jack", Address = "Shanghai"};            Thread t2 = new Thread (new ThreadStart (Userinfo.getuserinfo)); T2.            IsBackground = true; T2.            Start ();            A single parameter, using thread invocation, must be the object type thread t3 = new Thread (new Parameterizedthreadstart (GetName2)); T3.            IsBackground = true; T3.            Start ("Rolly");            Join to the thread pool queue, multiple parameters, use class or struct struct ThreadPool.QueueUserWorkItem (getuserinfo, userInfo);        Console.ReadLine (); }//No parameter 1 public staticvoid GetName1 () {Console.WriteLine ("No parameter 1:my name is jay!"); }//has a parameter, the parameter must be an object type public static void GetName2 (Object Name) {Console.WriteLine ("has arguments, so        Invoke with Thread: My name is "+ name.tostring ());            }//join to the thread pool, multiple parameters, use class or struct structure, parameter must be object type public static void GetUserInfo (Object obj) {            Strong turn UserInfo model = (UserInfo) obj; Console.WriteLine ("Multiple arguments, using thread invocation: My name is" + model.) Name + ", Address:" + model.        Address);        }} public class UserInfo {public string Name {get; set;}        public string Address {get; set;} public void GetUserInfo () {Console.WriteLine ("Calls within multiple parameter classes: My name is" + name + ", Address:" + addres        s); }    }}

V. Task class

Using ThreadPool's QueueUserWorkItem () method to initiate an asynchronous thread execution is simple, but the biggest problem with this method is that there is no built-in mechanism to let you know when the operation is complete, and there is no built-in mechanism to get a return value after the operation is complete. To do this, you can use the task class in System.Threading.Tasks.

Constructs a Task<tresult> object and passes the return type of an operation for the generic TResult parameter.

Namespace test{    class program    {        static void Main (string[] args)        {            task<int32> t = new Task <Int32> (n = Sum ((Int32) n), +);            T.start ();            T.wait ();            Console.WriteLine (T.result);            Console.readkey ();        }        private static Int32 sum (Int32 N)        {            Int32 sum = 0;            for (; n > 0;--n)                checked{sum + = n;}//Result too large, throw exception            return sum        ;    }}}

Once a task is completed, it can start another task, overriding the preceding code, without blocking any threads.

Namespace test{    class program    {        static void Main (string[] args)        {            task<int32> t = new Task <Int32> (n = Sum ((Int32) n), +);            T.start ();            T.wait ();            Task cwt = t.continuewith (Task = Console.WriteLine ("The result is {0}", T.result));            Console.readkey ();        }        private static Int32 sum (Int32 N)        {            Int32 sum = 0;            for (; n > 0;--n)                checked{sum + = n;}//result overflow, throw exception            return sum        ;    }}}

Vi. delegate Asynchronous execution

asynchronous invocation of Delegates: BeginInvoke () and EndInvoke ()

Namespace test{public    delegate string MyDelegate (object data);    Class program    {        static void Main (string[] args)        {            MyDelegate mydelegate = new MyDelegate (TestMethod); C6/>iasyncresult result = MyDelegate. BeginInvoke ("Thread Param", Testcallback, "Callback Param");            Asynchronous execution completes            string resultstr = MyDelegate. EndInvoke (result);        }        Thread function public        static string TestMethod (object data)        {            string datastr = data As String;            return datastr;        }        The async callback function public        static void Testcallback (IAsyncResult data)        {            Console.WriteLine (data). asyncstate);}}}    

Seven, thread synchronization

1) Atomic operation (interlocked): All methods perform one atomic read or one write operation.

2) the Lock () statement: Avoid locking the public type, otherwise the instance will go beyond the scope of code control and define the private object to be locked.

3) monitor for thread synchronization

by Monitor.Enter () and Monitor.Exit (), the acquisition and release of the exclusive lock is achieved, and the other threads are not allowed to access the resource.

There is also a TryEnter method that does not block the wait when the resource is requested, can set the time-out period, and cannot get the direct return false.

4) ReaderWriterLock

When the resource operation reads much less, in order to improve the utilization of resources, so that the read operation lock is a shared lock, multiple threads can read the resources concurrently, and the write operation is an exclusive lock, only one thread allowed to operate.

5) event class for synchronization

The event class has two states, the terminating state and the non-terminating state, when the terminating state is called WaitOne can request success, and set the time state to the signaled state.

1) AutoResetEvent (Automatic reset event)

2) ManualResetEvent (manual reset event)

6) Signal Volume (Semaphore)

The semaphore is an int variable maintained by the kernel object, which is 0 o'clock, the thread is blocked, the blocking is greater than 0 o'clock, and when the waiting thread on one semaphore is unblocked, the semaphore counts +1.

The thread will reduce the signal volume by 1 by WaitOne and add 1 to the signal via release, which is simple to use.

7) Mutex (mutex)

Exclusive resources, usage similar to semaphore.

8) Inter-process synchronization

System-level synchronization can be achieved by setting the name of the synchronization object, and different applications recognize different synchronization objects by synchronizing the names of the objects.

Source: http://www.cnblogs.com/luxiaoxun/p/3280146.html

Multi-threaded Learning (i)

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.