WinForm Development summarizes the necessity of using threads for 1>winform programs, and how to use them correctly

Source: Internet
Author: User

The necessity of using threads in a WinForm program:

Single-threaded operations can cause the interface to feign animation when performing time-consuming tasks, resulting in a very poor user experience, and sometimes even affecting normal business execution, and using multithreading to do something is a last resort.

One point that must be understood before writing a program is that the UI of the form can be manipulated only by the UI thread , and other threads will report an exception if they are going to perform a change in the control's value in the form or any other "action related to the form thread", as everyone knows. In order to adapt to this feature, it has been written as follows:

  private void Button1_Click (object sender, EventArgs e)        {this            . BeginInvoke (New Action (delegate ()            {                this.button1.Text = "Test";            }));        

It is obvious that the following code is executed in this form, that is to say, the code in parentheses is executed in the UI thread, and if it is just a simple task, there is no problem, because the time is fast enough to give the impression that the form does not pretend to be suspended. Now change the code to the following:

  private void Button1_Click (object sender, EventArgs e)        {this            . BeginInvoke (New Action (delegate ()            {for                (int i = 0; i <; i++)                {                    this.button1.Text = i.tostring (); C7/>thread.sleep (+);})            );        }

The expected execution result should be that every second button on the top of the text will be added 1 to 100, but the result is not so, when the button is clicked, the window into the suspended animation state, click will not have any response. This article is to solve such a problem. The main is to do a simple summary, spare.

The simplest and most brutal way to handle such a problem is to ignore the other threads without being able to execute the UI. The code is very simple, just need to add the following code in the interface initialization can be,

 public   Form1 () {Initializecompon            ENT (); Checkforillegalcrossthreadcalls  = false    ;//time to catch a call to the wrong thread ...        Ignoring the nature allows the form thread to be accessed from other threads.  private  void  button1_click (object   sender, EventArgs e) {Thread T = new  Thread (() => {this . Button1. Text =  "  test  "             ;            });        T.start (); }

This way is actually done can be in different threads to manipulate the form thread, but there is no egg, encountered in the case of the top of the situation every second to let the number of buttons from one, still can not do.

Please look back at the color of the sentence.

And then look at what Invoke,begininvoke really is:

Direct F12 find the interpretation of the signature

////Summary://executes the specified delegate asynchronously on the thread that creates the control's underlying handle. ////Parameters://Method://a delegate to a method without parameters. ////return Result://a System.IAsyncResult that represents the result of the System.Windows.Forms.Control.BeginInvoke (System.Delegate) operation. ////Exception://System.InvalidOperationException://the appropriate window handle could not be found. [Editorbrowsable (editorbrowsablestate.advanced)] PublicIAsyncResult BeginInvoke (Delegate method);
//        // Summary:         //      executes the specified delegate on the thread that owns the underlying window handle for this control.         //        // Parameters:         // Method    :        //      delegate that contains the methods to invoke in the thread context of the control.         //        // return Result:         // The      return value of the delegate being invoked, or null if the delegate has no return value. public        object Invoke (Delegate method);

Keyword: Executes the execution of the delegate on the thread that owns the underlying window handle for this control. The difference between synchronous async

This. BeginInvoke (New Action (Delegate ()

            {for                (int i = 0; i < i++)                {                    this.button1.Text = i.tostring ();                    Thread.Sleep (+);                })            );

So here's what it means to do button.text=i.tostring in the form thread, and then have the form thread hibernate for 1000 milliseconds, and the form will naturally not respond to your actions, whether it's asynchronous or not, in the form thread, The obvious problem is here, and now that we know where the problem lies. The solution is also very simple, that is,

Let all the tasks unrelated to the form do not execute in the form thread, all the actions of the form-related actions are all put into the form thread to execute, everyone's way, the problem naturally solved. Just the button text plus 1 per second, you can use the following way to write:

 Private voidButton1_Click (Objectsender, EventArgs e) {Thread T=NewThread (() =            {                 for(inti =0; I < -; i++) {Thread.Sleep ( +);  This. button1. Invoke (NewAction (Delegate()                    {                         This. button1. Text =i.tostring ();                }));            }             });        T.start (); }

Yes, that's it, a new thread is opened, so that all operations are executed inline, where there is a corresponding operation to the form thread that involves an action on the form, or something like this

  PublicForm1 () {InitializeComponent (); Checkforillegalcrossthreadcalls=false;//Ignore errors from other threads executing UI}Private voidButton1_Click (Objectsender, EventArgs e) {Thread T=NewThread (() =            {                 for(inti =0; I < -; i++) {Thread.Sleep ( +);  This. button1. Text =i.tostring ();            }            });        T.start (); }

This is obviously a bit trickery, and in some cases it can cause the form to blink and may be unstable, such as multiple threads executing a button's text display at the same time, but at least it's not as cumbersome to write in this way. As to how to choose the specific problem of specific analysis and treatment.

WinForm Development summarizes the necessity of using threads for 1>winform programs, and how to use them correctly

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.