asp.net backgroundworker download files in the background _ practical tips

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 the user clicks the Download button, the Click event handler invokes the RunWorkerAsync method of the BackgroundWorker component to start the download operation. During the download process, the button is disabled and then enabled after the download is complete. MessageBox will display the contents of the file.
Copy Code code 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;
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 to enable the button.
This.dowloadButton.Enabled = true;
}
private void Backgroundworker1_dowork (
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 to
Simulate a noticeable latency.
Thread.Sleep (5000);
}
private void backgroundworker1_runworkercompleted (
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 being used.
</summary>
<param name= "disposing" >true if managed resources should is 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 to Designer support-do not modify
The contents is 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.backgroundworker1_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 is for the application.
</summary>
[STAThread]
static void Main ()
{
Application.enablevisualstyles ();
Application.Run (New Form1 ());
}
}

Download file:
The file download occurs on the BackgroundWorker component's worker thread, which runs the DoWork event handler. This thread is started when the code calls the RunWorkerAsync method.
Copy Code code as follows:

private void Backgroundworker1_dowork (
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 to
Simulate a noticeable latency.
Thread.Sleep (5000);
}

Waiting for BackgroundWorker to complete
The Dowloadbutton_click event handler demonstrates how to wait for the BackgroundWorker component to complete its asynchronous task. Use the IsBusy property to determine whether the BackgroundWorker thread is still running. If the code is on the main UI thread (as for the Click event handler), be sure to call the Application.doevents method so that the user interface responds to user actions.
Copy Code code 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;
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 to enable the button.
This.dowloadButton.Enabled = true;
}

Show results
The Backgroundworker1_runworkercompleted method handles the RunWorkerCompleted event and is invoked after the background operation completes. It first checks the Asynccompletedeventargs.error property, and if the property is null, it displays the contents of the file.
Copy Code code as follows:

private void backgroundworker1_runworkercompleted (
object sender,
Runworkercompletedeventargs e)
{
if (e.error = = null)
{
MessageBox.Show (document). INNERXML, "Download Complete");
}
Else
{
MessageBox.Show (
"Failed to download File",
"Download Failed",
MessageBox Buttons.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.