Asp.net BackgroundWorker: download files in the background

Source: Internet
Author: User

Example:
The following code example demonstrates how to use the BackgroundWorker component to load an XML file from a URL. When you Click the "Download" button, the Click event handler calls the RunWorkerAsync method of the BackgroundWorker component to start the download operation. This button is disabled during the download process, and then enabled after the download is complete. MessageBox will display the file content.
Copy codeThe Code is as follows:
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. backgroundworker+dowork );
This. backgroundWorker1.RunWorkerCompleted + = new System. ComponentModel. RunWorkerCompletedEventHandler (this. backgroundWorker1_RunWorkerCompleted );
//
// 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:
The file is downloaded to the auxiliary thread of the BackgroundWorker component, which runs the DoWork event processing program. This thread is started when the Code calls the RunWorkerAsync method.
Copy codeThe Code is as follows:
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 );
}

Wait for the BackgroundWorker to finish
The dowloadButton_Click event handler demonstrates how to wait for the BackgroundWorker component to complete its asynchronous tasks. The IsBusy attribute can be used to determine whether the BackgroundWorker thread is still running. If the code is on the main UI thread (this is true for Click Event Handlers), you must call the Application. DoEvents method so that the user interface can respond to user operations.
Copy codeThe Code is as follows:
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
The backgroundworkercompleted method processes the RunWorkerCompleted event and is called after the background operation is complete. It first checks the AsyncCompletedEventArgs. Error attribute. If this attribute is null, it displays the file content.
Copy codeThe Code is as follows:
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 );
}
}

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.