C # display a new form in the thread

Source: Internet
Author: User

In multiple threads, some results must be displayed at the end of a thread. I use a new form to display the results. But simply write the following in the thread body:

 

  1 private void ThreadFunc()
2 {
3 MsgForm msg = new MsgForm();
4 msg.Show();
5 }
6 private void button1_Click(object sender, System.EventArgs e)
7 {
8 FormThread = new Thread(new ThreadStart(ThreadFunc));
9 FormThread.Start();
10 }

 

 

The generated form is lost in a flash. This is because all the resources in the form created in the thread belong to this thread, so when this thread ends, its resources are also recycled, of course, C # automatically closes the form.

The correct method is to use Invoke. The Code is as follows:

 

  1 private void ThreadFunc()
2 {
3 MethodInvoker mi = new MethodInvoker(this.ShowMsgForm);
4 this.BeginInvoke(mi);
5 }
6 private void ShowMsgForm()
7 {
8 MsgForm msg = new MsgForm();
9 msg.Show();
10 }
11 private void button1_Click(object sender, System.EventArgs e)
12 {
13 FormThread = new Thread(new ThreadStart(ThreadFunc));
14 FormThread.Start();
15 }

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.