asp.net BackgroundWorker之在后臺下載文件
更新時間:2011年12月23日 00:14:25 作者:
下載文件是常見任務,通常情況下,最好以單獨的線程來運行這項可能很耗時的操作。使用 BackgroundWorker 組件可以用非常少的代碼完成此任務
示例:
下面的代碼示例演示如何使用 BackgroundWorker 組件從 URL 加載 XML 文件。用戶單擊“下載”按鈕時,Click 事件處理程序將調用 BackgroundWorker 組件的 RunWorkerAsync 方法來啟動下載操作。在下載過程中,將禁用該按鈕,然后在下載完成后再啟用該按鈕。MessageBox 將顯示文件的內容。
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 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 resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should 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.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 for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.Run(new Form1());
}
}
下載文件:
文件下載在 BackgroundWorker 組件的輔助線程上進行,該線程運行 DoWork 事件處理程序。當代碼調用 RunWorkerAsync 方法時,將啟動此線程。
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);
}
等待 BackgroundWorker 完成
dowloadButton_Click 事件處理程序演示如何等待 BackgroundWorker 組件完成它的異步任務。使用 IsBusy 屬性可以確定 BackgroundWorker 線程是否仍在運行。如果代碼在主 UI 線程上(對于 Click 事件處理程序即是如此),請務必調用 Application.DoEvents 方法以使用戶界面能夠響應用戶操作。
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;
}
顯示結果
backgroundWorker1_RunWorkerCompleted 方法將處理 RunWorkerCompleted 事件,并在后臺操作完成后被調用。它首先檢查 AsyncCompletedEventArgs.Error 屬性,如果該屬性是 null,它將顯示文件內容。
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 );
}
}
下面的代碼示例演示如何使用 BackgroundWorker 組件從 URL 加載 XML 文件。用戶單擊“下載”按鈕時,Click 事件處理程序將調用 BackgroundWorker 組件的 RunWorkerAsync 方法來啟動下載操作。在下載過程中,將禁用該按鈕,然后在下載完成后再啟用該按鈕。MessageBox 將顯示文件的內容。
復制代碼 代碼如下:
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 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 resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should 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.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 for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.Run(new Form1());
}
}
下載文件:
文件下載在 BackgroundWorker 組件的輔助線程上進行,該線程運行 DoWork 事件處理程序。當代碼調用 RunWorkerAsync 方法時,將啟動此線程。
復制代碼 代碼如下:
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);
}
等待 BackgroundWorker 完成
dowloadButton_Click 事件處理程序演示如何等待 BackgroundWorker 組件完成它的異步任務。使用 IsBusy 屬性可以確定 BackgroundWorker 線程是否仍在運行。如果代碼在主 UI 線程上(對于 Click 事件處理程序即是如此),請務必調用 Application.DoEvents 方法以使用戶界面能夠響應用戶操作。
復制代碼 代碼如下:
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;
}
顯示結果
backgroundWorker1_RunWorkerCompleted 方法將處理 RunWorkerCompleted 事件,并在后臺操作完成后被調用。它首先檢查 AsyncCompletedEventArgs.Error 屬性,如果該屬性是 null,它將顯示文件內容。
復制代碼 代碼如下:
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 );
}
}
您可能感興趣的文章:
- C#中BackgroundWorker類用法總結
- c# BackgroundWorker組件的作用
- C#中backgroundWorker類的用法詳解
- c# BackgroundWorker使用方法
- C# BackgroundWorker使用教程
- C#使用后臺線程BackgroundWorker處理任務的總結
- C#中backgroundworker的使用教程
- C# BackgroundWorker用法詳解
- WinForm中BackgroundWorker控件用法簡單實例
- c#異步操作后臺運行(backgroundworker類)示例
- C#在后臺運行操作(BackgroundWorker用法)示例分享
- C# BackgroundWorker組件學習入門介紹
- 簡單使用BackgroundWorker創(chuàng)建多個線程的教程
- C#使用BackgroundWorker控件
相關文章
WPF中button按鈕同時點擊多次觸發(fā)click解決方法
這篇文章主要為大家詳細介紹了WPF中button按鈕同時點擊多次觸發(fā)click的解決方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-04-04ASP.NET?Core中Razor頁面與MVC區(qū)別介紹
這篇文章介紹了ASP.NET?Core中Razor頁面與MVC的區(qū)別,文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-02-02ASP.NET網站使用Kindeditor富文本編輯器配置步驟
首先下載編輯器然后部署編輯器最后在網頁中加入(ValidateRequest="false")引入腳本文件,具體配置步驟如下,有需求的朋友可以了解下哈2013-06-06使用Fiddler調試visual studion多個虛擬站點的問題分析
本篇文章小編為大家介紹,使用Fiddler調試visual studion多個虛擬站點的問題分析。需要的朋友參考下2013-04-04GridView分頁的實現(xiàn)以及自定義分頁樣式功能實例
本文為大家詳細介紹下GridView實現(xiàn)分頁并自定義的分頁樣式,具體示例代碼如下,有想學習的朋友可以參考下哈,希望對大家有所幫助2013-07-07