Backgroundworker: download files in the background

Source: Internet
Author: User

Downloading files is a common task. Generally, it is better to run this operation in a separate thread, which may be time-consuming. UseBackgroundworkerVery few components can be usedCodeComplete this task.

Example:

The following code example demonstrates how to use Backgroundworker The component loads the XML file from the URL. Click "Download" Button, Click Event Processing Program Call Backgroundworker Component Runworkerasync Method to start the download operation. This button is disabled during the download process, and then enabled after the download is complete. MessageBox The file content is displayed.
 Using System; Using System. Collections. Generic; Using System. componentmodel; Using System. drawing; Using System. Threading; Using System. Windows. forms; Using System. xml; Public   Class Form1: FORM { Private Backgroundworker backgroundworker1; Private Button dowloadbutton; Private Xmldocument document = Null ; Public Form1 () {initializecomponent ();} Private   Void Dowloadbutton_click ( Object Sender, eventargs e ){ // Start the download operation in the background.          This . Backgroundworker1.runworkerasync (); // Disable the button for the duration of the download.          This . Dowloadbutton. Enabled = False ; // Wait for the backgroundworker to finish the download.          While (This . Backgroundworker1.isbusy ){ // Keep UI messages moving, so the form remains              // Responsive during the asynchronous operation. Application. doevents ();} // The download is done, so enable the button.          This . Dowloadbutton. Enabled = True ;} Private   Void Backgroundworkerincludowork ( Object Sender, doworkeventargs e) {document = New Xmldocument (); // Replace this file name with a valid file name. Document. Load ( @ Http://www.tailspintoys.com/sample.xml" ); // Uncomment the following line          // Simulate a noticeable latency.          // Thread. Sleep (5000 ); } Private   Void Backgroundworkerappsrunworkercompleted ( Object Sender, runworkercompletedeventargs e ){ If (E. Error = Null ) {MessageBox. Show (document. innerxml, "Download complete" );} Else {MessageBox. Show ( "Failed to download file" , "Download failed" , Messageboxbuttons. OK, messageboxicon. Error );}} ///   <Summary>      ///  Required designer variable.      ///   </Summary>      Private System. componentmodel. icontainer components = Null ; ///   <Summary>      ///  Clean up any resources being used.      ///   </Summary>      ///   <Param name = "disposing">  True if managed resources shocould be disposed; otherwise, false. </param>      Protected   Override   Void Dispose ( Bool Disposing ){ If (Disposing & (components! = Null ) {Components. Dispose ();} Base . Dispose (disposing );} # Region Windows Form Designer generated code ///   <Summary>      ///  Required Method for designer support-do not modify      ///  The contents of this method with the code editor.      ///  </Summary>      Private   Void Initializecomponent (){ This . Backgroundworker1 = New System. componentmodel. backgroundworker (); This . Dowloadbutton = New System. Windows. Forms. Button (); This . Suspendlayout (); //          // Backgroundworker1          //          This . Backgroundworker1.dowork + =New System. componentmodel. doworkeventhandler ( This . Backgroundworkerjavasdowork ); This . Backgroundworker1.runworkercompleted + = New System. componentmodel. runworkercompletedeventhandler ( This . Backgroundworkerappsrunworkercompleted ); //          // Dowloadbutton          //          This . Dowloadbutton. Location = New System. Drawing. Point (12, 12 ); This . Dowloadbutton. Name = "Dowloadbutton" ; This . Dowloadbutton. size = New System. Drawing. Size (75, 23 ); This . Dowloadbutton. tabindex = 0; This . Dowloadbutton. Text = "Download file" ; This . Dowloadbutton. usevisualstylebackcolor = True ; This . Dowloadbutton. Click + = New System. eventhandler (This . Dowloadbutton_click ); //          // Form1          //          This . Autoscaledimensions = New System. Drawing. sizef (6f, 13f ); This . Autoscalemode = system. Windows. Forms. autoscalemode. Font; This . Clientsize = New System. Drawing. Size (104, 54 ); This . Controls. Add ( This . Dowloadbutton ); This . Name = "Form1" ; This . Text = "Form1" ; This . Resumelayout ( False );} # Endregion } Static   Class Program { ///   <Summary>      ///  The main entry point for the application.      ///  </Summary> [Stathread] Static   Void Main () {application. enablevisualstyles (); application. Run ( New Form1 ());}}
 
Download file:

Download the file inBackgroundworkerThe worker thread of the component.DoworkEvent Handler. When the code is calledRunworkerasyncThis thread is started.

Private VoidBackgroundworkerincludowork (ObjectSender, doworkeventargs e) {document =NewXmldocument ();// Replace this file name with a valid file name.Document. Load (@ Http://www.tailspintoys.com/sample.xml");// Uncomment the following line// Simulate a noticeable latency.// Thread. Sleep (5000 );}

Wait for the backgroundworker to finish

Dowloadbutton_clickEvent Handler demonstrates how to waitBackgroundworkerThe component completes its asynchronous tasks. UseIsbusyAttributes can be determinedBackgroundworkerWhether the thread is still running. If the code is on the main UI thread (ClickThis is true for the event handler), so be sure to callApplication.DoeventsMethod to enable the user interface to respond to user operations.

 Private   Void Dowloadbutton_click ( Object Sender, eventargs e ){ // Start the download operation in the background.      This . Backgroundworker1.runworkerasync (); // Disable the button for the duration of the download.      This . Dowloadbutton. Enabled = False ; // Wait for the backgroundworker to finish the download.      While ( This . Backgroundworker1.isbusy ){ // Keep UI messages moving, so the form remains          // Responsive during the asynchronous operation. Application. doevents ();} // The download is done, so enable the button.      This . Dowloadbutton. Enabled = True ;}

Display result

BackgroundworkerappsrunworkercompletedMethod will be processedRunworkercompletedEvent, which is called after the background operation is complete. It first checksAsynccompletedeventargs.ErrorProperty. If the property isNull, It will display the file content.

 
Private VoidBackgroundworkerappsrunworkercompleted (ObjectSender, runworkercompletedeventargs e ){If(E. Error =Null) {MessageBox. Show (document. innerxml,"Download complete");}Else{MessageBox. Show ("Failed to download file","Download failed", Messageboxbuttons. OK, messageboxicon. Error );}}

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.