In Silverlight, extremely time-consuming operations will lead to the UI process being suspended. If complicated operations and UI display are separated, and we need to know the current running Progress of the background process of this complex operation? Here we can use backgroundworker to solve this problem.
Backgroundworker is an encapsulated thread component that allows you to easily start an independent thread to execute complex and time-consuming background work, report the current completion level at any time, and stop asynchronous thread operations at any time, you can also access the UI thread in the response event of Asynchronous Operation Status Report (progresschanged) and runworkercompleted after the asynchronous operation is completed.
Some common attributes, methods, and events of backgroundworker are as follows:
• Attribute
Cancellationpending gets a value indicating the applicationProgramWhether the background operation has been canceled.
Isbusy gets a value indicating whether the backgroundworker is running an asynchronous operation.
Workerreportsprogress gets or sets a value that indicates whether backgroundworker can report progress updates.
Workersuppscanscancellation gets or sets a value that indicates whether backgroundworker supports asynchronous cancellation.
• Method
Cancelasync requests to cancel pending background operations.
Reportprogress raises the progresschanged event.
Runworkerasync starts background operations.
• Events
Dowork calls runworkerasync.
Progresschanged occurs when reportprogress is called.
Runworkercompleted occurs when the background operation is completed, canceled, or exception is thrown.
Now let's clear the running idea of this component:
1. Create a backgroundworker object instance, set its properties workerreportsprogress, workersuppscanscancellation to ture, and load corresponding event handling methods for dowork, progresschanged, and runworkercompleted events of the backgroundworker instance.
2. At this time, press the "run button" to determine whether the current object is already running background asynchronous threads Based on the isbusy attribute of backgroundworker. If no asynchronous thread is executed, runworkerasync () is called () the method starts to execute the asynchronous thread and can pass the parameter A. At this time, the dowork event is triggered. In this event, the UI thread cannot be operated directly. In this case, check whether the cancellationpending attribute is true within the dowork response time. If it is true, the asynchronous process has been canceled. Otherwise, the complex operation to be processed can be continued through E. the argument property receives parameter.
3. Execute the reportprogress (INT percentprogress) function once every other period of time during complex operations, pass the current running completion percentage, which is parameter B, and then trigger the progresschanged event, in this event, E. the progresspercentage property receives parameter B, updates the UI's progressbar control, and displays the current progress of completion.
4. After complex operations in dowork are completed, assign C to E. Result of the current dowork event, and then trigger the runworkercompleted event. In this case, the value of E. result is accepted in the runworkercompleted event. Display the result on the UI.
Next let's take a look at the instance program source code mainpage. XAML. cs. The relevant running notes are inCodeAlready noted:
Public Partial Class Mainpage: usercontrol
{
// Declare a backgroundworker object instance
Private Backgroundworker bgworker = New Backgroundworker ();
Public Mainpage ()
{
Initializecomponent ();
Initbackgroundworker ();
}
// Initialize attributes and load events of backgroundworker
Public Void Initbackgroundworker ()
{
// Does backgroundworker support reporting progress?
Bgworker. workerreportsprogress = True ;
// Does backgroundworker support canceling asynchronous operations?
Bgworker. workersuppscanscancellation = True ;
// Load dowork, progresschanged, runworkercompleted events
Bgworker. dowork + = New Doworkeventhandler (bgworker_dowork );
Bgworker. progresschanged + = New Progresschangedeventhandler (bgworker_progresschanged );
Bgworker. runworkercompleted + = New Runworkercompletedeventhandler (bgworker_runworkercompleted );
}
// Asynchronous operations in the background
Void Bgworker_dowork ( Object Sender, doworkeventargs E)
{
// Get passed parameters
String Str = E. argument. tostring ();
// Execute 100 cycles
For ( Int I = 0 ; I < 100 ; I ++ )
{
// Determine whether the asynchronous operation of the current backgroundworker has been canceled
If (Bgworker. cancellationpending = False )
{
// If the asynchronous operation is not canceled, the thread blocks the following and reports it to the bgworker_progresschanged event.
Thread. Sleep ( 50 );
Bgworker. reportprogress (I + 1 );
E. Result = " 3322 " ;
}
Else
{
// Set the asynchronous thread operation that has been canceled
E. Cancel = True ;
Break ;
}
}
}
// The event execution function triggered when the progress changes. The execution progress is displayed here.
Void Bgworker_progresschanged ( Object Sender, progresschangedeventargs E)
{
// Set the value of the current progress bar to the event execution completion level.
This . Progressbar1.value = E. progresspercentage;
}
// Processing after the asynchronous operation is completed
Void Bgworker_runworkercompleted ( Object Sender, runworkercompletedeventargs E)
{
// After completing the asynchronous operation, check whether the asynchronous operation is canceled. A prompt is displayed.
If (E. cancelled = True )
{
MessageBox. Show ( " Cancel asynchronous thread operation " );
}
Else
{
MessageBox. Show ( " Asynchronous thread execution completed " + E. Result );
}
This . Btncancel. Content = " Completed " ;
}
Private Void Btnrun_click ( Object Sender, routedeventargs E)
{
// If the background process does not start running, the running thread starts.
If (Bgworker. isbusy ! = True )
{
Bgworker. runworkerasync ( " Parameters " );
}
}
Private Void Btncancel_click ( Object Sender, routedeventargs E)
{
// Cancels asynchronous operations.
Bgworker. cancelasync ();
}
}
This instance is written in vs2010 + Silverlight 4.0. Click slbackgroundworker_caleung.rar to download the source code of this instance.