Thread pool (C #)

Source: Internet
Author: User

Transferred from: http://blog.sina.com.cn/s/blog_494305f30100ryw7.html

Here you can learn that Microsoft is studying the principle mechanism of the CLR implementation thread pool, thus more flexible processing of the CLR in the actual code should be the thread pool of the problem, let's take a look.

The creation of the thread pool of the CLR tutorial

When the CLR initializes, its thread pool does not contain a wired thread. When an application wants to create a thread to perform a task, the application should request the thread pool threads to perform the task. When the thread pool knows, it will create an initial thread.

The new thread undergoes the same initialization as the other threads, but after the task is completed, the thread does not destroy itself. Instead, it returns the thread pool in a suspended state. If the application makes a request to the thread pool again, the suspended thread activates and executes the task without creating a new thread. This saves a lot of overhead.

As long as the application tasks in the thread pool are queued faster than a single thread handles each task, you can reuse the same threads over and over again, saving significant overhead during the lifetime of the application.

If the application task in the thread pool is queued more quickly than a single thread is processing the task, the thread pooling creates additional threads. Of course, creating a new thread does incur additional overhead, but the application is likely to request only a few threads in its lifetime to handle all the tasks entrusted to it. Therefore, in general, you can improve the performance of your application by using a thread pool.

A wonderful feature of the thread pool is that it is heuristic. If your application needs to perform many tasks, the thread pool will create more threads. If your application's workload is decreasing, thread pool threads will terminate themselves. The thread pool algorithm ensures that it contains only the number of threads required for the workload placed on it!

Therefore, I hope you now understand the basic concept of the thread pool and understand the performance benefits it can provide. Now I'll give some code to illustrate how to use the thread pool. First, you should know that the thread pool can provide four functions:

1> Asynchronous Call method

2> calling a method at a certain time interval

3> calling a method when a single Kernel object gets a signal notification

4> calling a method when an asynchronous I/O request ends

The first three features are very useful and I'll explain them in this column. The fourth feature is rarely used by application developers, so I'm not going to explain it here, and it might be in a future column.

function 1:CLR thread pool Tutorial Asynchronous invocation method

In your application, if you have code that creates a new thread to perform the task, then I recommend that you replace it with a new code that executes the task with the command thread pool. In fact, you will often find it easier to have a thread pool perform tasks than to make a new dedicated thread perform tasks.

To queue a thread pool task, you can use the ThreadPool class that is defined in the System.Threading namespace. (The ThreadPool class provides only static methods and cannot construct instances of it)

For thread pool threads to invoke methods asynchronously, your code must call a ThreadPool overloaded QueueUserWorkItem () method, as follows:

public static Boolean QueueUserWorkItem (WaitCallback WC, Object State);

public static Boolean QueueUserWorkItem (WaitCallback WC);

These methods queue work items (and optional state data) to threads in the thread pool and return immediately. A work item is just a method (identified by the WC parameter) that is called and passed to a single parameter, state (state data)

A queueuserworkitem version without a status parameter passes NULL to the callback method. Finally, some threads in the pool will call your method to process the work item.

Note: The callback method must match the System.Threading.WaitCallback delegate type, which is defined as follows:

public delegate void WaitCallback (Object state);

code example:

[CSharp]View Plaincopy
  1. Using System;
  2. Using System.Threading;
  3. Public class Test
  4. {
  5. //field that holds the numeric value to be calculated
  6. static Double dRes1 =-1;
  7. static Double dRes2 =-1;
  8. public static void Main ()
  9. {
  10. //Gets the maximum number of threads for the thread pool and the minimum number of idle threads maintained
  11. int maxthreadnum, portthreadnum;
  12. int minthreadnum;
  13. Threadpool.getmaxthreads (outmaxthreadnum, out portthreadnum);
  14. Threadpool.getminthreads (outminthreadnum, out portthreadnum);
  15. Console.WriteLine ("Maximum number of threads: {0}", Maxthreadnum);
  16. Console.WriteLine ("Minimum number of idle threads: {0}", Minthreadnum);
  17. //function variable value
  18. int x = 15600;
  19. //Start the first task: Calculate X's 8-Time Square
  20. Console.WriteLine ("Start the first task: Calculate 8 times for {0}.")  ", x);
  21. ThreadPool.QueueUserWorkItem (new WaitCallback (TaskProc1), x);
  22. //Start a second task: Calculate the 8 root of x
  23. Console.WriteLine ("Start the second task: Calculate the 8 root of the {0}.")  ", x);
  24. ThreadPool.QueueUserWorkItem (new WaitCallback (TASKPROC2), x);
  25. //Wait until two values are calculated
  26. while (dRes1 = =-1 | | dRes2 = =-1);
  27. //Print calculation results
  28. Console.WriteLine ({1}, {2} ", X, DRes1, DRes2) for the 8-and 8-square-root of" {0} "respectively;
  29. }
  30. //Start the first task: Calculate X's 8-Time Square
  31. static void TaskProc1 (object o)
  32. {
  33. DRes1 = Math.pow (convert.todouble (o), 8);
  34. }
  35. //Start a second task: Calculate the 8 root of x
  36. static void TaskProc2 (object o)
  37. {
  38. DRes2 = Math.pow (convert.todouble (o), 1.0/8.0);
  39. }
  40. }

function 2:CLR thread pool tutorial to invoke a method at a certain time interval

If your application needs to perform a task at a certain time, or if your application needs to perform certain methods on a regular basis, then using the thread pool will be your best choice.

The System.Threading namespace defines the Timer class. When you construct an instance of the Timer class, you are telling the thread pool that you want to callback your own method at a specific time in the future.

There are four kinds of constructors for the Timer class:

Public Timer (TimerCallback callback, Object State, Int32 duetime, Int32 period);

Public Timer (TimerCallback callback, Object State, UInt32 duetime, UInt32 period);

Public Timer (TimerCallback callback, Object State, Int64 duetime, Int64 period);

Public Timer (TimerCallback callback, Object State, TimeSpan duetime, TimeSpan period);

All of these four constructors construct exactly the same Timer object. The callback parameter identifies the method that you want to be recalled by thread pool threads.

Note: The callback method must match the System.Threading.TimerCallback delegate type, which is defined as follows:

public delegate void TimerCallback (Object state);

After the Timer object is constructed, the thread pool knows what to do and automatically monitors the time for you.

However, the Timer class also provides several other methods that allow you to communicate with the thread pool so that you can change when (or whether) the callback method should be used. Specifically, the Timer class provides several change and Dispose methods:

Public Boolean Change (Int32 duetime, Int32 period);

Public Boolean Change (UInt32 duetime, UInt32 period);

Public Boolean Change (Int64 duetime, Int64 period);

Public Boolean Change (TimeSpan duetime, TimeSpan period);

Public Boolean Dispose (); Public Boolean Dispose (WaitHandle notifyobject);

The change method allows you to alter the duetime and period of the Timer object;

The Dispose method allows you to completely cancel the callback when all pending callbacks have been completed, and optionally signal the kernel object identified by the Notifyobject parameter.

function 3:CLR thread pool teaching method to invoke when a single kernel object gets a signal notification

To get the thread pool threads to call your callback method when the kernel object is signaled, you can reuse some of the static methods defined in the System.Threading.ThreadPool class.

To have thread pool threads call methods when a kernel object is signaled, your code must call an overloaded Registerwaithandle method

Function: Register a delegate waiting for WaitHandle

Function Prototypes:

executeOnlyOnce)

Parameters:

1> Waitobject identifies the kernel object that you want the thread pool to wait for.

Because this parameter is an abstract base class System.Threading.WaitHandle, you can specify any class that derives from that base class.

In particular, you can pass a reference to the AutoResetEvent, ManualResetEvent, or Mutex object

2> CallBack identifies the method that you want the thread pool threads to call.

Note: The callback method must match the System.Threading.WaitOrTimerCallback delegate type, which is defined as shown in the following line of code:

public delegate void WaitOrTimerCallback (Object state, Boolean timedout);

3> state allows you to specify certain status data that should be passed to the callback method, passing NULL if no special state data is being passed;

4> milliseconds allows you to tell the thread pool when the kernel object should wait before it gets signaled. Here usually pass-1, to indicate blocking waits.

5> executeOnlyOnce Indicates whether the callback function is executed multiple times or once

If the value is true, then thread pool threads will only execute the callback method once;

If the value is false, the thread pool threads will execute the callback method each time the kernel object is signaled. This is useful for AutoResetEvent objects.

return value:

The method returns a Registeredwaithandle object. The object determines the kernel object that the thread pool is waiting on. If for some reason your application tells the thread pool to stop monitoring registered wait handles, your application can call Registeredwaithandle's Unregister method:

Public Boolean Unregister (WaitHandle waitobject);

The Waitobject parameter indicates how you want to get a signal notification when all work items in the queue have been executed.

If you do not want a signal notification, you should pass NULL to the parameter. If you pass a valid reference to the Waithandle-derived object, the thread pool notifies the object when all pending work items that have been registered for the wait handle have finished executing.

Summary

In this column, I describe the need for a thread pool, and explain how to take advantage of the various features provided by the CLR thread pool. Now you should understand the value that the thread pool brings to your development, which can improve the performance of your application and simplify your code.

Thread pool (C #)

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.