C # asynchronous multithreading (access to the main program-controlled component)

Source: Internet
Author: User

In the case of multiple threads, other threads cannot directly call controls on the main thread. They can only call controls on the main thread through proxies.

1. Define Delegation
// Delegate statement for executing the task (solving the long task death false)
Delegate void RunTaskDelegate (int seconds );
// Display the delegate Declaration of the progress bar (cross-thread Call Control)
Delegate void ShowProgressDelegate (int totalStep, int currentStep );
2. Definition Method
Private void ShowProgress (int totalStep, int currentStep)
{
ProgressBar1.Maximum = totalStep;
ProgressBar1.Value = currentStep;
}
3. Define a thread
Private void RunTask (int seconds)
{
ShowProgressDelegate showProgress = new ShowProgressDelegate (ShowProgress );
For (int I = 0; I <seconds * 4; I ++)
{
Thread. Sleep (250 );
// Call the delegate that displays the progress bar in the basic window
This. Invoke (showProgress, new object [] {seconds * 4, I + 1 });
}
}
4. Execute
RunTaskDelegate runTask = new RunTaskDelegate (RunTask );
// Call the task delegate Asynchronously
RunTask. BeginInvoke (20, null, null );

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.