C # multithreaded Tour (3)

Source: Internet
Author: User
Tags call back

Read Catalogue

    • Code download
    • first, Introduction
    • Ii. entering the thread pool through TPL
    • third, no TPL into the thread pool
V Blog Preface

First to explain the background, write the "c # multi-threaded tour" This series of articles mainly because of the following reasons:1. Multithreading in the c/s and b/s architecture is used very much ; 2. And the use of multithreading is very complex, if not used well, easy to cause a lot of problems.

V Written in front

multithreading, advantages and disadvantages, use need to be cautious.

V Body Start

Original Address: C # multithreaded Tour (3)--thread Pool

C # multithreaded Tour (1)--introduction and basic concepts

C # multithreaded Tour (2)--create and start threads

C # multithreaded Tour (3)--thread Pool

C # multithreaded Tour (4) a tentative study OF--APM

C # multithreaded Tour (5)--introduction to the synchronization mechanism

C # Multithreaded Tour (6)--a detailed description of locks in multiple threads

More articles are being updated, so please look forward to ...

C # multithreaded Tour (3)--thread Pool

Back to the top of the code download

Thread_ Blog Park _cnblogs_jackson0714.zip

code example for the first ~ third Article:

SOURCE Address: Https://github.com/Jackson0714/Threads

Back to top one, introduction

No matter when you start a thread, hundreds of milliseconds will be spent tidying up a new local variable stack. Each thread consumes 1MB of memory by default . The thread pool cuts these overhead by sharing and recycling threads, allowing multithreading to be applied at a very granular level without loss of performance. This is useful when taking full advantage of multi-core systems to execute parallel code that is computationally Intensive.

The thread pool also maintains a limit on the total number of threads, which allows the threading to run more Smoothly. Too many threads will cause administrative burdens and cause the CPU cache to be small, causing the operating system to not Run. Once a limit arrives, thejob waits until another completion begins. This makes it possible for any parallel application, such as a Web server(the synchronization method is an advanced technique that can be used more efficiently by threads in the thread pool).

Here are a few ways to get into the thread pool:

    1. Through the Task Parallel Library(. NET 4.0)
    2. By calling ThreadPool.QueueUserWorkItem
    3. By Asynchronous Delegates
    4. by Backgroundworkder

The following structure uses the thread pool directly:

    1. Wcf,remoting,asp.net,asmx WEB Services Application servers
    2. System.Timers.Timer and System.Threading.Timer
    3. The Framework methods is terminated by Async, such as WebClient (the event-based asynchronous Pattern) and most of the BeginXXX Method (the Asynchronous Programming model Pattern)
    4. Plinq

Task Parallel Library (TPL) and PLINQ are fully effective and high-grade, and even when the thread pool is unimportant, you will also want to use them to assist with multithreading.

Now let's take a quick look at how we use the Task class to implement a simple delegate that runs on a thread pool.

Here's What to look for when using the thread pool:

    1. You cannot set the name of a thread because setting the name of the thread will make debugging more difficult ( even if you can attach a description when you are debugging in the VS thread window).
    2. Threads in the thread pool are always background threads (this is usually not a problem).
    3. Blocking a thread may trigger a delay during the start of the application, unless you call threadpool.setminthreads

You cannot arbitrarily change the priority of a thread in a pool - because the priority is reverted to normal when it releases the Pool.

You can query whether the thread is a thread in a pool that is running through property Thread.CurrentThread.IsThreadPoolThread Properties

Back to Topii. entering the thread pool through TPL

You can use the Task class in the Taskparallel Library to easily enter the thread Pool. This Task class is described in the Framework 4.0 : If you are familiar with the old structure, consider replacing the non-generic task class with ThreadPool.QueueUserWorkItem, replace the asunchoronous delgates with the generic task< Tresult>. The latest structure is faster, more convenient, and more Complex.

To use a non-generic task class, call the Task.Factory.StartNew method and pass the method into the Delegate.

Task.Factory.StartNew returns a task object that you can use to monitor the task, forexample, You can call its wait method until it finishes.

static void Main (string[] Args) {task task =  Task.Factory.StartNew (Go); Wait (); Console.readkey ();} static void Go () {console.writeline ("from the thread pool start ..."); Thread.Sleep (3000); Console.WriteLine ("from the thread pool end");}

When you invoke the Wait method for a task, an unhandled exception is easily re-thrown onto the host Thread. (if you do not call the Wait method but discard the task, an unhandled exception will shut down the Process)

The generic task<tresult> class is a subclass of a non-generic Task. It lets you get a return value from this task that has already been executed. In the following example, we use task<tresult> to download a Web page

static void Main (string[] Args) {task<string> Task = task.factory.startnew<string> (() = downloadstring ( "http://www.baidu.com"));//call other Methods////can Use the property of the result of the task to obtain the task return Value. If the task is still running, the current main thread will be blocked until the task is Completed. string result = Task. Result;} static string downloadstring (string Uri) {using (var WC = new System.Net.WebClient ()) {return wc. Downloadstring (uri);}}

The Task Parallel Library has many functions, especially to improve the performance of multi-core Processors. We will continue to discuss TPL in parallel programming.

Back to Topthird, no TPL into the thread pool

If your application is an earlier version of The. NET Framework ( prior to 4.0), you will not be able to use the TPL. You must use the old structure to enter the thread pool:

ThreadPool.QueueUserWorkItem and asynchoronous delegates. The difference between the two is that asynchronous delegates lets you return data from the THREAD. Asynchronous delegates collects any exception returned to the Caller.

To use QueueUserWorkItem, simply call this method to run the delegate on the thread Pool.

static void Main (string[] Args) {threadpool.queueuserworkitem (Go); ThreadPool.QueueUserWorkItem (Go, 123); Console.readkey ();} static void Go (object Data) {console.writeline ("A from thread pool!" + data);}

Our target method Go, must receive a simple object type parameter (in order to satisfy the WaitCallback delegate). This will provide a simple way to pass the data into the method, just like the parameterizedthreadstart. Unlike a Task,QueueUserWorkItem does not return an object to help you manage execution later. also, you must explicitly write code in the target Method's code to handle the exception - because an unhandled exception will terminate the Program.

ThreadPool.QueueUserWorkItem does not provide a mechanism to get its return value from an already completed Thread. Asynchronous delegate invocations (asynchronous delegates for Short) solves this problem by allowing any number of typed parameters to be passed in two Directions. In addition, unhandled exceptions on asynchronous delegates are easily re-thrown on the original thread (more precisely, this thread is called EndInvoke), so there is no need to display processing.

Do not confuse asynchronous delegates and asynchronous method (methods begin with begin and end, such as file.beginread/file.endread). Asynchronous methods are superficially based on simple protocols, but they exist to solve a more difficult problem.

Here's How to start a worker task with a asynchronous delegate:

    1. Instantiates a delegate for the method that you want to run in parallel func delegates
    2. Delegatebegininvoke Iasyncresult return Value. begininvoke
    3. When you need this result, call ZH-CN endinvokedelegateiasyncresult object.

In the following example, we use a asynchronous delegate invocation to run a simple method that runs concurrently with the main thread, and this method returns the length of a string:

static void Main (string[] Args) {func<string, int> t = go;iasyncresult result = T.begininvoke ("test", null, null);/// / ... Other parallel tasks can be performed here//int length = T.endinvoke (result); Console.WriteLine ("String lenth is:" + length); Console.readkey ();} static int Go (string Messsage) {return messsage. Length;}

EndInvoke do three things. first, if asynchronous delegate does not complete execution, it waits for it to Complete. second, receive the return value (as well as any ref or out parameters). third, return any unhandled thread exceptions to the thread that called it.

Note: If you use asynchronous delegate to invoke a method that does not return a value, you need to call EndInvoke technically. In practice, This is an open debate; no endinvoke alarm to manage punishment not compiled by! If you choose not to call endinvoke, however, you need to consider the exception of the thread to avoid a silent failure.

When you invoke the BeginInvoke method, You can specify a call back delegate- a method that can receive a IAsyncResult object. It will be called automatically after the delegate method is completed, which allows the thread that is being started to forget asynchronous Delegate, but it needs a little extra work at the end of call Back.

V written in the last

Thread pool use of the promotion has not been written, the last two years of irregular routines, programmers have to raise the body, early to bed and early to Bed. Hope this blog can help everyone, hope to get the support of the garden friends!


Author: Jackson0714
Source: http://www.cnblogs.com/jackson0714/
About project development that focuses on Microsoft Platforms. If you have any questions or suggestions, please enlighten me!
Copyright Notice: This article is copyright to the author and the blog Park is shared, welcome reprint, but without the consent of the author must retain this paragraph, and in the article page obvious location to give the original Link.
It is hereby stated that all comments and private messages will be answered at the first Time. Also welcome the garden of the big to correct mistakes, common progress. or direct messages to Me.
Supporters: If you feel that the article is helpful, you can click "recommend" in the lower right corner of the Article. Your encouragement is the ultimate motivation for the author to insist on original and continuous writing!

C # multithreaded Tour (3)

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.