C # Multithreading

Source: Internet
Author: User
Tags instance method

One, shared variables between threads:
      1. Variables in the same object (thread internal methods)
classThreadTest {BOOLDone ; Static voidMain () {threadtest TT=NewThreadTest ();//Create a common instance        NewThread (TT. Go).        Start (); Tt.    Go (); }    //Note that Go was now an instance method    voidGo () {if(!Done ) { Done=true; Console.WriteLine (" Done"); }    }}
      1. static variables
classThreadTest {Static BOOLDone//Static Fields is shared between all threads    Static voidMain () {NewThread (Go).        Start ();    Go (); }    Static voidGo () {if(!Done ) { Done=true; Console.WriteLine (" Done"); }    }}
Join & Sleep
    1. After the Join waits for the thread to finish executing.
    2. Sleep pauses the current thread for a while, sleep (0) & Yield is the same, set the current process to the waiting state, and give the CPU to other threads.
Passing parameters
  1. anonymous function
     Thread t = new  Thread (() = Print ( " hello from t!   "  new  Thread (() => {...}". Start ();  new  Thread (delegate  () {...}). Start (); 
  2. Start function
    New Thread (Print). Start ("Hello from t! " ); Static void Print (object// function parameter can only be object type
  3. Notice the change of the parameters
     for (int0new Thread (() =0223557799
Thread naming
    1. Name the current thread
      " Main ";
    2. naming Other threads
      New"worker";
foreground thread and background thread (Foreground Threads & Background Threads)
    1. The foreground thread can prevent the program from exiting. The CLR does not close the program unless all foreground threads are finished. (default foreground of thread created by yourself)
    2. Background threads are sometimes called Daemon thread. He is considered by the CLR to be an unimportant execution path that can be discarded at any time. So when all the foreground threads are finished, the CLR closes the program even if there is a background thread executing. (Threads in thread pool default background)

The front and back of the thread is independent of the thread's priority.

Sometimes you need to wait for the background thread to complete and exit the program, such as freeing up resources, as follows:

    1. If the thread is created by itself, you can use the Join function
    2. If the thread is in the thread pool, you can use the Wait event
Thread priority threads have the following precedence:
Enum

Raising the priority of a thread requires careful consideration because it can cause a deadlock in the resource.

The priority of a thread is under the priority of the process, and if the A1 thread in a process wants to compete for resources with the B1 thread in the B process, the priority of the a process should be increased first:

using (Process p =

Processpriorityclass.high is the highest level of the process, and if your process is set to high and enters an infinite loop, the operating system will be locked. For this reason, high is generally used for real-time system Realtime, and the process will not transfer the CPU to any process after it enters the time wheel.

Exception handling

Exception handling try/catch/finally need to be written inside the function, otherwise it will cause the main program to crash, the program exits directly.

Thread pool

Creating threads through tread consumes time to organize resource creation threads and consumes memory. Threads that use the thread pool do not have these problems. Enter the thread pool mode:

    1. Task Parallel Library (TPL. net4.0+)
    2. Call ThreadPool.QueueUserWorkItem
    3. Asynchronous delegate (asynchronous delegates)
    4. by BackgroundWorker

The following indirectly uses a thread pool to build:

    1. WCF, Remoting, ASP. NET, ASMX Web service services
    2. System.Timers.Timer & System.Threading.Timer
    3. Framework methods such as WebClient, most of the beginxxx, and other asynchronous methods
    4. Plinq

Use the thread pool to be aware of:

    1. Threads in the thread pool are not named and debugging is difficult
    2. Threads in the thread pool are background threads
    3. Early in the application life cycle, blocking threads can cause additional delays.

Queries whether the current thread is in the threads pool: Thread.CurrentThread.IsThreadPoolThread.

Using the thread pool
  1. task Parallel Library (TPL. net4.0+)
     Task.Factory.StartNew (Go, arg1, arg2 ...); 

    go parameter can be not an object type

    receive return parameter Task<tresult>:

     task<string  > Task = Task.factory.startnew<string  > (() = downloadstring (  Http://www.linqpad.net    string  result = task. Result; // use The result, block the main thread until the task finished  

     

  2. Call ThreadPool.QueueUserWorkItem

    When used. NET is 4.0 versions, we can only use ThreadPool.QueueUserWorkItem and asynchronous delegates two ways.

  3. Asynchronous delegate (asynchronous delegates)

    The difference from ThreadPool.QueueUserWorkItem is that the asynchronous delegates can receive the returned result, and the exception can be handled uniformly in the main thread.

    1. Instantiating a delegate
    2. Call the delegate's BeginInvoke, use IAsyncResult to receive the return value
    3. When you need to use the return result, call the delegate's EndInvoke and pass the saved IAsyncResult object.

    EndInvoke three things to do:

    1. Waits for the asynchronous delegate execution to complete.
    2. Receive return results (including ref & out parameters)
    3. Throws an exception to the main thread.

    Split implementation:

    Method is passed in BeginInvoke, passing through IAsyncResult.AsyncState. Where IAsyncResult.AsyncState is an object type, you can pass any variable.

C # Multithreading

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.