asp.net BackgroundWorker之在后臺(tái)下載文件
更新時(shí)間:2011年12月23日 00:14:25 作者:
下載文件是常見(jiàn)任務(wù),通常情況下,最好以單獨(dú)的線(xiàn)程來(lái)運(yùn)行這項(xiàng)可能很耗時(shí)的操作。使用 BackgroundWorker 組件可以用非常少的代碼完成此任務(wù)
示例:
下面的代碼示例演示如何使用 BackgroundWorker 組件從 URL 加載 XML 文件。用戶(hù)單擊“下載”按鈕時(shí),Click 事件處理程序?qū)⒄{(diào)用 BackgroundWorker 組件的 RunWorkerAsync 方法來(lái)啟動(dòng)下載操作。在下載過(guò)程中,將禁用該按鈕,然后在下載完成后再啟用該按鈕。MessageBox 將顯示文件的內(nèi)容。
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 組件的輔助線(xiàn)程上進(jìn)行,該線(xiàn)程運(yùn)行 DoWork 事件處理程序。當(dāng)代碼調(diào)用 RunWorkerAsync 方法時(shí),將啟動(dòng)此線(xiàn)程。
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 組件完成它的異步任務(wù)。使用 IsBusy 屬性可以確定 BackgroundWorker 線(xiàn)程是否仍在運(yùn)行。如果代碼在主 UI 線(xiàn)程上(對(duì)于 Click 事件處理程序即是如此),請(qǐng)務(wù)必調(diào)用 Application.DoEvents 方法以使用戶(hù)界面能夠響應(yīng)用戶(hù)操作。
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;
}
顯示結(jié)果
backgroundWorker1_RunWorkerCompleted 方法將處理 RunWorkerCompleted 事件,并在后臺(tái)操作完成后被調(diào)用。它首先檢查 AsyncCompletedEventArgs.Error 屬性,如果該屬性是 null,它將顯示文件內(nèi)容。
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 文件。用戶(hù)單擊“下載”按鈕時(shí),Click 事件處理程序?qū)⒄{(diào)用 BackgroundWorker 組件的 RunWorkerAsync 方法來(lái)啟動(dòng)下載操作。在下載過(guò)程中,將禁用該按鈕,然后在下載完成后再啟用該按鈕。MessageBox 將顯示文件的內(nèi)容。
復(fù)制代碼 代碼如下:
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 組件的輔助線(xiàn)程上進(jìn)行,該線(xiàn)程運(yùn)行 DoWork 事件處理程序。當(dāng)代碼調(diào)用 RunWorkerAsync 方法時(shí),將啟動(dòng)此線(xiàn)程。
復(fù)制代碼 代碼如下:
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 組件完成它的異步任務(wù)。使用 IsBusy 屬性可以確定 BackgroundWorker 線(xiàn)程是否仍在運(yùn)行。如果代碼在主 UI 線(xiàn)程上(對(duì)于 Click 事件處理程序即是如此),請(qǐng)務(wù)必調(diào)用 Application.DoEvents 方法以使用戶(hù)界面能夠響應(yīng)用戶(hù)操作。
復(fù)制代碼 代碼如下:
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;
}
顯示結(jié)果
backgroundWorker1_RunWorkerCompleted 方法將處理 RunWorkerCompleted 事件,并在后臺(tái)操作完成后被調(diào)用。它首先檢查 AsyncCompletedEventArgs.Error 屬性,如果該屬性是 null,它將顯示文件內(nèi)容。
復(fù)制代碼 代碼如下:
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類(lèi)用法總結(jié)
- c# BackgroundWorker組件的作用
- C#中backgroundWorker類(lèi)的用法詳解
- c# BackgroundWorker使用方法
- C# BackgroundWorker使用教程
- C#使用后臺(tái)線(xiàn)程BackgroundWorker處理任務(wù)的總結(jié)
- C#中backgroundworker的使用教程
- C# BackgroundWorker用法詳解
- WinForm中BackgroundWorker控件用法簡(jiǎn)單實(shí)例
- c#異步操作后臺(tái)運(yùn)行(backgroundworker類(lèi))示例
- C#在后臺(tái)運(yùn)行操作(BackgroundWorker用法)示例分享
- C# BackgroundWorker組件學(xué)習(xí)入門(mén)介紹
- 簡(jiǎn)單使用BackgroundWorker創(chuàng)建多個(gè)線(xiàn)程的教程
- C#使用BackgroundWorker控件
相關(guān)文章
Net5?WorkService?繼承?Quarzt?及?Net5處理文件上傳功能
這篇文章主要介紹了Net5?WorkService?繼承?Quarzt?以及?Net5處理文件上傳,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-02-02
C# GetWindowRect簡(jiǎn)介及使用說(shuō)明
GetWindowRect返回指定窗口的邊框矩形的尺寸。該尺寸以相對(duì)于屏幕坐標(biāo)左上角的屏幕坐標(biāo)給出,需要的朋友可以了解下2012-12-12
.net搜索查詢(xún)并實(shí)現(xiàn)分頁(yè)實(shí)例
.net搜索查詢(xún)并實(shí)現(xiàn)分頁(yè)實(shí)例,需要的朋友可以參考一下2013-03-03
在ASP.Net Core中使用Lamar的全過(guò)程
這篇文章主要給大家介紹了關(guān)于在ASP.Net Core中使用Lamar的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-03-03
如何創(chuàng)建一個(gè)AJAXControlToolKit的擴(kuò)展控件
相信熟悉Microsoft提供的AJAXControlToolKit的朋友已經(jīng)感覺(jué)到它的強(qiáng)大了。但是如果我們需要其它一些控件,或者是我們碰到一些很好的javascript然后需要把它們整合到ajaxcontroltoolkit中,如何來(lái)做。???2009-08-08
asp.net動(dòng)態(tài)生成HTML表單的方法
這篇文章主要介紹了asp.net動(dòng)態(tài)生成HTML表單的方法,結(jié)合實(shí)例形式分析了asp.net動(dòng)態(tài)生成HTML表單的相關(guān)控件使用技巧與注意事項(xiàng),需要的朋友可以參考下2017-03-03
ASP.NET MVC 迅速集成 SignalR的過(guò)程
在ASP.NET MVC項(xiàng)目中集成SignalR可以實(shí)現(xiàn)定時(shí)任務(wù)操作數(shù)據(jù)庫(kù)并將數(shù)據(jù)實(shí)時(shí)更新到網(wǎng)頁(yè),通過(guò)創(chuàng)建新項(xiàng)目、配置SignalR、操作數(shù)據(jù)庫(kù)、創(chuàng)建SignalR Hub和定時(shí)任務(wù),可以實(shí)現(xiàn)前端頁(yè)面的實(shí)時(shí)數(shù)據(jù)顯示,本文提供了詳細(xì)的步驟和代碼示例,幫助開(kāi)發(fā)者快速實(shí)現(xiàn)實(shí)時(shí)數(shù)據(jù)更新功能2024-09-09
MVC微信網(wǎng)頁(yè)授權(quán)獲取用戶(hù)OpenId
這篇文章主要為大家詳細(xì)介紹了MVC微信網(wǎng)頁(yè)授權(quán),在模板頁(yè)中獲取用戶(hù)openid,感興趣的小伙伴們可以參考一下2016-09-09

