时间:2021-05-20
c#异步操作,BackgroundWorker类的使用,可以在后台运行需要的代码逻辑。
复制代码 代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace TestBackgroundWork
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
InitializeBackgoundWorker();
}
private BackgroundWorker backgroundWorker1;
private void InitializeBackgoundWorker()
{
this.backgroundWorker1 = new System.ComponentModel.BackgroundWorker();
this.backgroundWorker1.WorkerReportsProgress = true;
this.backgroundWorker1.WorkerSupportsCancellation = true;
this.backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
this.backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
this.backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
}
//**********backgroundWorker1的回调函数**********
void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
for (int i = 1; i <= 10; i++)
{
if (worker.CancellationPending)
{
e.Cancel = true;
}
else
{
Thread.Sleep(500);
int percentComplete = (int)((float)i / (float)10 * 100);
worker.ReportProgress(percentComplete);
}
}
}
void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
this.progressBar1.Value = e.ProgressPercentage;
}
void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Error != null)
{
MessageBox.Show(e.Error.Message);
}
else if (e.Cancelled)
{
resultLabel.Text = "Canceled";
}
else
{
resultLabel.Text = "Completed";
}
startBtn.Enabled = true;
stopBtn.Enabled = false;
}
//**********backgroundWorker1的回调函数**********
private void startBtn_Click(object sender, EventArgs e)
{
resultLabel.Text = String.Empty;
this.startBtn.Enabled = false;
this.stopBtn.Enabled = true;
//启动异步操作.
backgroundWorker1.RunWorkerAsync();
}
private void stopBtn_Click(object sender, EventArgs e)
{
backgroundWorker1.CancelAsync();
}
}
}
声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。
介绍:根据MSDN介绍:BackgroundWorker类允许您在单独的专用线程上运行操作。耗时的操作(如下载和数据库事务)在长时间运行时可能会导致用户界面(U
在C#当中,利用WebClient这个核心类,可以轻易的打造一个下载器。但是这里想要强调的是,我们用的是异步操作。所谓异步,是相对于同步的概念而言的。比如Web
C#不是C语言,C#是Microsoft公司主推的,C#是类C的语言,因此与C有许多地方语言法上相似。C#是托管的,只能运行在.net平台上,而且C语言不是。
本文实例为大家分享了C#操作INI配置文件示例的具体代码,供大家参考,具体内容如下源文件地址:C#操作INI配置文件示例创建如图所示的控件:源代码:usingS
本文实例讲述了C#操作session的类。分享给大家供大家参考。具体分析如下:这个C#类对session操作进行了再次封装,可以大大简化session的常用操作