Thread Generation 10, without explicitly calling the thread, thread situation

Source: Internet
Author: User

Thread Generation 10, without explicitly calling the thread, thread situation

Generally, we create a thread through the thread constructor before using the thread. In fact, some methods provided by. NET classes use multithreading internally. Some classes that encapsulate multithreading and asynchronous processing methods comply with "event-based asynchronous pattern )". For the BackgroundWorker class under System. ComponentModel, this class conforms to this mode.

 

BackgroundWorker class attributes:
Workersuppscanscancellation: Set to true to allow cancellation.
WorkerReportProgress: Set to true to show progress

 

BackgroundWorker events:
DoWork: what the background thread needs to do
ProgressChanged: Progress trigger event
RunWorkerCompleted: triggered when the progress ends, an exception is thrown, or the execution is canceled.

 

For example, the BackgroundWorker class is used in Windows Forms applications.

→ Create a Windows form application. The interface includes two buttons, one label, one progressbar, and one BackgournWorker control.

→ Set the workersuppscanscancellation attribute of the BackgournWorker control and WorkerReportProgress to true.

→ The background code is:

       private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            int sum = 0;
            for (int i = 1; i <=100; i++)
            {
                Thread.Sleep(1000);
                sum = sum + 1;
                backgroundWorker1.ReportProgress(i);
// If the calculation is canceled
                if (backgroundWorker1.CancellationPending)
                {
                    e.Cancel = true;
                    backgroundWorker1.ReportProgress(0);
                    return;
                }
                e.Result = sum;
            }
        }
        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
// Display the BackgroundWorker process to the ProgressBar
            progressBar1.Value = e.ProgressPercentage;
// Display the BackgroundWorker process to the label
            label1.Text = e.ProgressPercentage + "%";
        }
        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
If (e. Cancelled) // may end with cancellation
            {
Label1.Text = "computing canceled ";
            }
Else if (e. Error! = Null) // it may end with an exception thrown.
            {
                label1.Text = e.Error.Message;
            }
Else // may end normally
            {
Label1.Text = "1 to 100:" + e. Result. ToString ();
            }
        }
// Start Calculation
        private void btnCalculate_Click(object sender, EventArgs e)
        {
            if (!backgroundWorker1.IsBusy)
            {
                backgroundWorker1.RunWorkerAsync();
            }
        }
// Cancel Calculation
        private void btnCancel_Click(object sender, EventArgs e)
        {
            if (backgroundWorker1.IsBusy)
            {
                backgroundWorker1.CancelAsync();
            }
            
        }

 

In the DoWork event:
○ The instance method ReportProgress of BackgroundWorker is used to display the background thread progress to the progress bar.
○ Save the calculation Result of DoWork to the Result attribute of DoWorkEventArgs type.

 

In the ProgressChanged event:
○ Display the property values of the ProgressPercentage parameter of the event's ProgressChangedEventArgs type to the progress bar and label respectively.

 

In the RunWorkerCompleted event:
○ The Cancelled attribute value of the RunWorkerCompletedEventArgs type parameter of the event is used to determine whether the event is canceled.
○ The Error attribute value of the RunWorkerCompletedEventArgs type parameter is used to record exceptions.
○ The Result attribute value of the RunWorkerCompletedEventArgs type parameter is retrieved from the DoWork event and set for the Result attribute of the DoWorkEventArgs type.

 


Click "Start computing". The background thread runs and displays the progress bar and label.

 

The thread series includes:

Thread series 01, front-end thread, back-end thread, thread synchronization thread series 02, multiple threads simultaneously process a time-consuming task to save time thread series 03, multi-thread shared data, multi-thread data sharing

Thread series 04, passing data to the thread, thread naming, thread Exception Handling, thread pool thread series 05, manual end thread series 06, view the thread pool and Its thread series 07 through CLR code, use the lock statement block or Interlocked type method to ensure the data synchronization thread series 08 of the auto-Increment Variable, and implement various methods of thread lock, use lock, Montor, Mutex, Semaphore, and thread deadlock

Thread generation 09, thread waiting, notification, and manual control of the number of threads

Thread Generation 10, without explicitly calling the thread


N threads are waiting for execution

# Include "windows. h"
# Include "iostream. h"
DWORD ThreadId [10];
HANDLE Thread [10];
Int Operand = 0;
Int suffix;
Int I = 0;
CRITICAL_SECTION g_cs;
Dword winapi ThreadProc (
LPVOID lpParameter
);
Void CreateTh (DWORD suffix)

{

: CloseHandle (Thread [suffix]);
Thread [suffix] = CreateThread (NULL, 0, ThreadProc, & suffix, 0, & ThreadId [suffix]);

}

Dword winapi ThreadProc (
LPVOID lpParameter
)

{
: EnterCriticalSection (& g_cs );

If (Operand >= 1000)

Return 0;

Suffix = * (int *) lpParameter;

I = 0;

While (I <100)

{

Operand ++;

I ++;

Cout <Operand <endl;

: Sleep (100 );

}

: LeaveCriticalSection (& g_cs );
CreateTh (suffix );

Return 0;

}

Int main (int argc, char * argv [])
{
InitializeCriticalSection (& g_cs );
For (int I = 0; I <10; I ++)
{
Thread [I] =: CreateThread (NULL, 0, ThreadProc, & I, 0, & ThreadId [I]);

}
: Sleep (1000 );
WaitForMultipleObjects (10, Thread, true, INFINITE );
: DeleteCriticalSection (& g_cs );
For (I = 0; I <10; I ++)
: CloseHandle (Thread [I]);
Printf ("Hello, Word \ n ");
Return 0;
}

Here is an example of a 10000 thread used to traverse all files in the computer.

The above idea is to use 10 threads to process the same thing.

Create another thread with its own thread number and thread handle.

There are always 10 threads running in the certification system... the remaining full text>

Java thread

It is to create 10 threads in the main thread, retain each thread reference (it is best to use the set) and start them separately, and then call the join method of each thread, in this way, the following code runs after all the 10 threads are finished. Then create 10 threads (loop is recommended)

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.