C # cross-thread manipulation controls

Source: Internet
Author: User

When looking at someone else's code will always invoke and BeginInvoke method, although the general understanding of what the meaning, but not very good use, the Internet to check a lot of information, it happened to see their studies reprinted a blog post:

The difference between C#invoke and BeginInvoke

Blog post speak of some theoretical knowledge, this article introduces a few common problems:

Under the. NET Platform WinForm, WPF prohibits direct access to controls across threads, so it is asynchronous when you have to access controls across threads.

1. Access controls across threads in WinForm projects:

Write a WinForm Small instance: In a WinForm project, sometimes in order to display the state of the system running in real time into a form, add a RichTextBox control to display the system run log in real time. The operation in this example is to write the log as a string into the RichTextBox control, because it is displayed in real time and therefore involves cross-thread input issues.

Private Delegate voidSetrichtexbox (strings);  Public voidSetText (stringtxt) {            if( This. t_revmsg. invokerequired)//Waiting for asynchronous{Setrichtexbox FC=NewSetrichtexbox (Set);  This. Invoke (FC,New Object[]{txt}];            }            Else            {                 This. T_revmsg.            AppendText (TXT); }        }
Private voidSet (stringtxt) {t_revmsg. AppendText (TXT); }

When the value of the InvokeRequired control is true, it indicates that there is a thread that does not belong to the creation of it to access it, which requires an asynchronous operation.

2. Access controls across threads in a WPF project:

In the page for WPF, add a button control and a TextBox control, and click the button implementation for adding the contents of the TextBox control.

Private voidButton2_Click (Objectsender, RoutedEventArgs e) {             This. TextBox1.Dispatcher.Invoke (NewWritedelegate (Writemethod),"asdf"); }        Private Delegate voidWritedelegate (stringstr); Private voidWritemethod (stringstr) {             This. Textbox1.appendtext (str); }

3. Get the contents of a TextBox control across threads in a WPF project

The function of this example is: Click the button control to open the socket monitoring service. The listening port needs to be fetched from a textbox in the UI interface, because it is not accessed by the thread that created it, so it has dispatcher.invoke asynchronous operations. A little supplement: in the process of opening listening, there is a while (true) dead loop, directly into the main thread will cause the thread will not continue to work, the workaround is to open a new thread to open the listener.

Private voidButton1_Click (Objectsender, RoutedEventArgs e) {Thread Thread=NewThread (NewThreadStart (startserver)); Thread.        Start (); } Public voidStartServer () {intPort = Convert.ToInt32 (GetText ( This. Tbport)); ServerSocket ServerSocket=NewServerSocket (port);        Serversocket.start (); }Private Delegate stringGettexthandle (Control control); Private stringGetText (Control control) {if( This. Dispatcher.thread! =System.Threading.Thread.CurrentThread) {return(string) This. Dispatcher.invoke (NewGettexthandle ( This.            GetText), control); }            Else            {                if(Control. GetType () = =typeof(TextBox)) {                    return((TextBox) control).                Text; }                Else                {                    return string.                Empty; }            }        }

Summarize:

From the above examples, you can see that cross-threading calls require the use of Invoke and BeginInvoke (not used temporarily), and in some systems where the requirements are not very stringent, they are considered to be common. (I don't know, right?) Hope Master Pointing twos)

So far, there are only a few of the common problems encountered, and then add to it.

C # cross-thread manipulation controls

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.