C # WinForm multithreaded Development (ii) ThreadPool and Timer

Source: Internet
Author: User
Original address: Click to open the link

[ abstract ] This article describes the C # WinForm multithreaded development of ThreadPool and Timer, and provides detailed sample code for reference.

In this paper, we continue to explore the multi-threaded problem in WinForm, and then focus on ThreadPool and timer again.

First, ThreadPool

The thread pool (ThreadPool) is a relatively simple method that adapts to a number of short tasks that require multiple threads (such as some threads that are often in a blocking state), and its disadvantage is that the threads created cannot be controlled or prioritized. Since there is only one thread pool per process, and of course there is only one thread pool (snaplines) per application domain, you will find that the member functions of the ThreadPool class are static! When you first call ThreadPool.QueueUserWorkItem, ThreadPool.RegisterWaitForSingleObject, and so on, a thread pool instance is created. Here I will introduce two functions in the thread pool:


public static bool QueueUserWorkItem (//Call succeeds returns True     WaitCallback callback,//the thread to be created calls the delegate     object state// Arguments passed to the delegate     )//It is similar to another overloaded function, except that the delegate has no arguments

The purpose of this function is to queue threads to be created to the thread pool, create this thread when the thread pool's number of available threads is not zero (the line Cheng creates a limit of 25 threads), or it is queued to the thread pool until it has an available thread.

public static Registeredwaithandle RegisterWaitForSingleObject (     WaitHandle waitobject,//to register WaitHandle     WaitOrTimerCallback callback,//thread calls the delegate     object state,//passed to the delegate parameter     int timeout,//time-out, in milliseconds,     bool executeOnlyOnce//Whether to execute only once); public delegate void WaitOrTimerCallback (     object state,//is also a parameter that is passed to the delegate     bool Timedout//true is called because of a time-out, Conversely, it is because of waitobject);


The purpose of this function is to create a waiting thread that, once called, creates this thread, is in a "blocked" state until the parameter waitobject becomes signaled or the time timeout has been set, and it is worth noting that this "blocking" is very different from the WaitSleepJoin state of the thread: When a thread is in the WaitSleepJoin state, the CPU periodically wakes it up to poll the update status information and then enters the WaitSleepJoin state again, which is a resource-consuming switch. While the thread created with this function is different, the CPU does not switch to this thread before triggering it to run, it does not consume CPU time and does not waste thread switching time, but how does the CPU know when to run it? In fact, the thread pool generates a number of worker threads to monitor these trigger conditions, and when the condition is reached, the corresponding thread is started, and of course the worker threads themselves take time, but if you need to create more waiting threads, the advantage of using the thread pool becomes more pronounced.

More detailed Demo:

namespace testmethodinvoker{public partial class Form2:form {public Form2 () {Initializ        Ecomponent (); private void Button1_Click (object sender, EventArgs e) {//threadpool.registerwaitforsingleobje CT (//EV,//New WaitOrTimerCallback (Waitthreadfunc),//4,//20            XX,//false//indicates that the timer is reset every time the wait operation is completed until the logoff waits//);            ThreadPool.QueueUserWorkItem (New WaitCallback (ThreadFunc), "test1");        Thread.Sleep (10000);        } Private delegate void Myinvokedelegate (string name); private void Test (object o) {richtextbox1.text + = string.        Format ("The object is {0} \ n", O); } public void ThreadFunc (object b) {this.        Invoke (New Myinvokedelegate (Test), b); The public void Waitthreadfunc (object B, bool t) {richTextBox1.Text + = string. Format ("The objECT is {0},t are {1}\n ", B, t); }     }}

A well-deserved extension, here's invoke proxy, in fact there are other methods, such as action and Func. The instance code is as follows:

This. Invoke (New action<string> (this). Changetext), o.tostring ()); Invoke (New Action (delegate () {this.textBox1.Text = O.tostring ();})); private void DoSomething (object o) {    system.func<string, int> f = new func<string, int> (this. GETID);    Object result = this. Invoke (F, o.tostring ());    MessageBox.Show (result. ToString ());} private int GetId (string name) {    this.textBox1.Text = name;    if (name = = "Y")     {       return 999;    }    else     {        return 0;    }}

Second, Timer


It applies to methods that need to be called periodically, and it does not run in the thread that created the timer, it runs in a separate thread that is automatically assigned by the system. This is similar to the SetTimer method in Win32. It is constructed as:

Public Timer (     TimerCallback callback,//The method required to invoke     object state,//passed to the callback parameter     int duetime,// How long after the call callback     int period//Call this method time interval);//

If Duetime is 0, callback immediately executes its first call. If Duetime is Infinite, callback does not call its method. The timer is disabled, but you can re-enable it using the change method. If period is 0 or Infinite, and duetime is not Infinite, then callback calls its method one time. The periodic behavior of the timer is disabled, but you can re-enable it using the change method. If period is 0 (0) or Infinite, and duetime is not Infinite, then callback calls its method one time. The periodic behavior of the timer is disabled, but you can re-enable it using the change method.

If you want to change the period and duetime after the timer is created, we can change it by invoking the changing method of the timer:

public bool Change (     int duetime,     int period);//

The two parameters that are obviously changed correspond to the two parameters in the timer.


The above is C # WinForm Multithreading Development (ii) ThreadPool and timer content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • 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.