Multithreading, delegation, invoke solve the problem of WinForm interface card, and with switch

Source: Internet
Author: User

First, the Knowledge point 1, update the contents of the control, you should call the control's Invoke method. Invoke refers to executing the specified delegate with the specified argument list on the thread that owns the control's underlying window handle. The method receives a delegate type and a delegate's arguments, so the delegate type variable needs to be defined and then passed to the Invoke method. If another thread calls the method directly to update the contents of the control, an error: the inter-thread operation is invalid: it is accessed from a thread that is not creating the control "RichTextBox1". 2, the essence of a delegate is a method of a type that has the same parameters and return type. A delegate is similar to a function pointer in the C language, and can point to multiple functions of the same type. To define a delegate, simply precede the function return type with the delegate keyword and replace the contents of the function body brace {} with the component number. For example: public delegate void Delegatefun (String msg);D Elegatefun represents a function type that receives a string parameter and returns void. 3, open a thread, start directly, and then suspend and wake up to implement the pause function. Thread t = new thread (Run); T.start (); Starts by judging the thread state and deciding whether to wake the thread. if (t.threadstate = = threadstate.suspended)//If it is suspended, wake {T.resume ();} Suspend on suspend thread: T. Suspend (); Stop, Hang thread Note: You can also define a switch that controls the start and end, and continue directly when the switch is false, so that it behaves as a pause output, but the thread is actually running. Second, interface and code
usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Linq;usingSystem.Text;usingSystem.Windows.Forms;usingSystem.Threading;namespacewindowsformsapplication3{ Public Partial classForm2:form { PublicForm2 () {InitializeComponent (); }        /// <summary>        ///because the Invoke method of the control needs to receive the delegate variable, you need to define the delegate and delegate variables///defines a delegate that receives a parameter/// </summary>        /// <param name= "msg" ></param>         Public Delegate voidDelegatefun (stringmsg); /// <summary>        ///define a delegate variable///this delegate variable, which needs to be initialized to specify a specific method, is then passed to the control's Invoke method call. /// </summary>         PublicDelegatefun Fun1; /// <summary>        ///define a thread, process the data, and update the interface/// </summary>        PrivateThread T =NULL; //Start button        Private voidButton1_Click (Objectsender, EventArgs e) {             This. Invoke (FUN1,"start ..."); //Increase your judgment to avoid opening a thread each time you click            if(T = =NULL) {T=NewThread (Run);               T.start (); }            if(t.threadstate = = threadstate.suspended)//If it is suspended, it wakes up.{t.resume (); }                       }        //End Execution        Private voidButton2_Click (Objectsender, EventArgs e) {t.suspend ();//stop, suspend thread             This. Invoke (FUN1,"... Stop"); }                //a concrete way to do things         Public voidRun () {//...... Handle some things and then output the log            inti =0;  while(true) {i++; //This refers to Form2//invoke refers to executing the specified delegate with the specified argument list on the thread that owns the control's underlying window handle. //the argument to invoke is a delegate type, so the delegate variable must be defined                 This.                           Invoke (FUN1, i.ToString ()); }        }        //assigning a specific method to a delegate variable when the form is initialized        Private voidForm2_load (Objectsender, EventArgs e) {            //initialize a specific execution method to a delegate variableFUN1 =Print; }        //How to output logs         Public voidPrint (stringmsg) {            //This method cannot be called directly by a newly opened thread.            The reason is that the control can only be called by the thread that created it. //other thread invoke prompt error: invalid inter-thread operation: access it from a thread that is not creating the control "RichTextBox1".              This. Richtextbox1.appendtext (msg +"\ r \ n");  This. Richtextbox1.scrolltocaret (); }    }}

Third, refer to article 1, C # Multithreading solution interface to solve the problem of the perfect solution, BeginInvoke rather than entrust delegatehttp://www.sufeinet.com/thread-3556-1-1.html

Multithreading, delegation, invoke solve the problem of WinForm interface card, and with switch

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.