C # experiences of creating a new form in the Child thread (thread-safe call to Windows Form Controls)

Source: Internet
Author: User

I encountered the following problems when writing socket communication:

In addition to the main UI thread, a background socket listening thread keeps listening for new messages. When new messages arrive, a new window pops up in the lower right corner to remind users.

If a form is created and popped up using a listening thread, the listening thread is stuck in the listening status and does not have much time to process the UI.


Solution:

You should create a form on the main UI thread and call the Invoke () method through a form or control in the main thread to run the code for creating and displaying the form on the main UI thread,

// Define a delegate MessageEntity as the message entity class delegate void ShowMessageCallback (MessageEntity message); // The delegate method private void ShowMessageSmall (MessageEntity message) {// message box Form MessageSmall ms = new MessageSmall (message); ms. show () ;}// call the delegate private void show (MessageEntity message) {// create the delegate ShowMessageCallback wt = new ShowMessageCallback (ShowMessageSmall); // This code is written in the main form class, this indicates the main form. this. invoke (wt, new Object [] {message });}
After the listening thread monitors a message, it only needs to call the show method and pass a message entity to create a new window through the main UI thread.

You can also refer to the MSDN documentation:

Http://msdn.microsoft.com/zh-cn/library/ms171728%28v=vs.80%29.aspx

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.