Interaction between forms and subthreads.

Source: Internet
Author: User

Interaction between forms and subthreads.

Communication between forms and subthreads

By default, the UI on the form is not allowed to be controlled by subthreads (or other UI threads that do not create controls) (this is allowed under NET2.0, but considering security issues, this function is forbidden from 2.0, unless Form's checkforillegalcrossthreadcils = true, which is not recommended ).

So what should we do?

1) Use the Invoke or BeginInvoke method:

Use a thread to call the Invoke or BeginInvoke method:

Public partial class Form1: Form
{
Public void Processing (int num)
{
Int answer = 2;
Task t = new Task () =>
{
For (int I = 3; I <= num; I ++)
{
Answer * = I;
}
This. BeginInvoke (new MethodInvoker () => {Thread. Sleep (3000); MessageBox. Show ("Finished! ")}));
MessageBox. Show ("OK ");
});
T. Start ();
}
Public Form1 ()
{
InitializeComponent ();

}
Private void button#click (object sender, EventArgs e)
{
MessageBox. Show ("First! ");
Processing (10 );
}
}

Note the following:
1) BeginInvoke: the "Asynchronous" here is not for the UI thread, but when the Control BeginInvoke is called in a child thread, the code after BeginInvoke in the Child thread (the "Finished" box pops up) will be executed first, and then the Label will be assigned after the delegate method in BeginInvoke is fully executed. If it is changed to Invoke, "OK" is always executed after the Invoke delegate Code is fully executed.
Therefore, BeginInvoke = Invoke (in the UI main thread, so it is not recommended to directly call it in the main thread)

2) Synchronous SynchronizedContext:
Public partial class Form1: Form
{
Public void Processing (int num, SynchronizationContext context)
{
Int answer = 2;
Task t = new Task () =>
{
For (int I = 3; I <= num; I ++)
{
Answer * = I;
}
SynchronizationContext. SetSynchronizationContext (context );
SynchronizationContext. Current. Post (obj) => {Thread. Sleep (3000); MessageBox. Show ("Finished") ;}, null );
MessageBox. Show ("Last ");
});
T. Start ();
}
Public Form1 ()
{
InitializeComponent ();

}
Private void button#click (object sender, EventArgs e)
{
MessageBox. Show ("First! ");
Processing (10, SynchronizationContext. Current );
}
}

Similar to BeginInvoke and Invoke, note:
1) SynchronizationContext: it is automatically initialized only in the UI form thread (SynchronizationContext in the button1_Click event. current is the Current form). to interact with other threads, the new SynchronizationContext () must be used ).
2) The Post method is equivalent to the BeginInvoke method, and the Send method is equivalent to the Invoke method.

If you carefully experiment with the code, you will find that no matter what the situation, the pop-up "Finished" box is always "suspended" for 3 seconds, yes, it is proved that all the above four methods are executed on the UI thread (only synchronous or asynchronous messages are sent to the form message pump ). Therefore, we should "clean all the data in the subthread at one time (get the result before Invoke, BeginInvoke, Send or Post, and write the code), and then Send a notification to the form at one time, update the page ).

Note:

Any Delegate also has the BeginInvoke method, which is truly asynchronous. Once Invoke is implemented, it must be implemented by a thread.


C # subthread access to the main form Control

Yes,
You cannot call the control created by the main thread in other threads ~!!!!
This is not safe. Therefore, 2.0 blocks this ~

The upstairs is right. Use delegation. The specific code is as follows ~ :
Public delegate void MyInvoke (string str );

Private void button9_Click (object sender, EventArgs e)
{
// _ MyInvoke = new MyInvoke (SetText );
// Checkforillegalcrossthreadcils = false;
Thread t = new Thread (new ThreadStart (fun ));
T. Start ();
}

Private void fun ()
{
// _ MyInvoke ("dddd ");
SetText ("ddd ");
}
Private void SetText (string s)
{
If (textBox6.InvokeRequired)
{
MyInvoke _ myInvoke = new MyInvoke (SetText );
This. Invoke (_ myInvoke, new object [] {s });
}
Else
{
This. textBox6.Text = s;
}
}

C # How does a subthread access controls in a subform?

The control is declared as public.
Then you can obtain the reference of the form and access it directly. If the form is not created in a child thread, use Invoke to access it.

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.