using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.IO;
namespace backgroundworker
{
public partial class Form1 : Form
{
BackgroundWorker bgw = new BackgroundWorker();
public Form1()
{
InitializeComponent();
//绑定Dowork事件
//bgw.DoWork += Bgw_DoWork;
bgw.DoWork += backgroundWorker1_DoWork;
//绑定进度更新事件,需要配合WorkerReportsProgress的属性一起使用
bgw.ProgressChanged += Bgw_ProgressChanged;
bgw.WorkerReportsProgress = true;
//指示是否启用用户停止属性
bgw.WorkerSupportsCancellation = true;
bgw.RunWorkerCompleted += Bgw_RunWorkerCompleted;
this.progressBar1.Maximum = 100;
}
private void Bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
//如果用户取消了当前操作就关闭窗口。
//if (e.Cancelled)
//{
// this.Close();
//}
//计算已经结束,需要禁用取消按钮。
this.btn_Stop.Enabled = false;
//计算过程中的异常会被抓住,在这里可以进行处理。
if (e.Error != null)
{
Type errorType = e.Error.GetType();
switch (errorType.Name)
{
case "ArgumentNullException":
case "MyException":
//do something.
break;
default:
//do something.
break;
}
}
MessageBox.Show(e.Result.ToString());
//计算结果信息:e.Result
//use it do something.
}
/// <summary>
/// 更新UI界面
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Bgw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
this.progressBar1.Value = e.ProgressPercentage;
}
/// <summary>
/// Bgw_DoWork事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Bgw_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker bgWorker = sender as BackgroundWorker;
int endNumber = 0;
if (e.Argument != null)
{
endNumber = (int)e.Argument;
}
for (int i = 0; i < endNumber; i++)
{
Thread.Sleep(10);
bgWorker.ReportProgress(i);
e.Result = i;
//在操作的过程中需要检查用户是否取消了当前的操作。
if (bgWorker.CancellationPending == true)
{
e.Cancel = true;
break;
}
}
}
private void btn_Start_Click(object sender, EventArgs e)
{
FileInfo fi = new FileInfo(@"C:\Users\xiaowei.gong\Desktop\新建文件夹\123.txt");
MessageBox.Show("创建时间:" + fi.CreationTime.ToString() + " 写入文件的时间" +
fi.LastWriteTime + " 访问的时间" + fi.LastAccessTime);
//
if (bgw.IsBusy)
return;
this.progressBar1.Value = 0;
this.btn_Stop.Enabled = true;
bgw.RunWorkerAsync(2000);
}
private void btn_Stop_Click(object sender, EventArgs e)
{
bgw.CancelAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
// Do not access the form's BackgroundWorker reference directly.
// Instead, use the reference provided by the sender parameter.
BackgroundWorker bw = sender as BackgroundWorker;
// Extract the argument.
int arg = (int)e.Argument;
// Start the time-consuming operation.
e.Result = TimeConsumingOperation(bw, arg);
// If the operation was canceled by the user,
// set the DoWorkEventArgs.Cancel property to true.
if (bw.CancellationPending)
{
e.Cancel = true;
}
}
// This event handler demonstrates how to interpret
// the outcome of the asynchronous operation implemented
// in the DoWork event handler.
private void backgroundWorker1_RunWorkerCompleted(
object sender,
RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
// The user canceled the operation.
MessageBox.Show("Operation was canceled");
}
else if (e.Error != null)
{
// There was an error during the operation.
string msg = String.Format("An error occurred: {0}", e.Error.Message);
MessageBox.Show(msg);
}
else
{
// The operation completed normally.
string msg = String.Format("Result = {0}", e.Result);
MessageBox.Show(msg);
}
}
// This method models an operation that may take a long time
// to run. It can be cancelled, it can raise an exception,
// or it can exit normally and return a result. These outcomes
// are chosen randomly.
private int TimeConsumingOperation(
BackgroundWorker bw,
int sleepPeriod)
{
int result = 0;
Random rand = new Random();
while (!bw.CancellationPending)
{
bool exit = false;
int i = rand.Next(3);
bw.ReportProgress(i * 10);
switch (i)
{
// Raise an exception.
case 10:
{
throw new Exception("An error condition occurred.");
break;
}
// Sleep for the number of milliseconds
// specified by the sleepPeriod parameter.
case 1:
{
Thread.Sleep(sleepPeriod);
break;
}
// Exit and return normally.
case 2:
{
result = 23;
//exit = true;
break;
}
default:
{
break;
}
}
if (exit)
{
break;
}
}
return result;
}
}
}
BackgroundWorker使用
最新推荐文章于 2023-09-05 11:12:05 发布