C#中Backgroundworker与Thread的区别
public partial class MainWindow : Window
{
private BackgroundWorker m_BackgroundWorker;// 申明后台对象
public MainWindow()
{
InitializeComponent();
m_BackgroundWorker = new BackgroundWorker(); // 实例化后台对象
m_BackgroundWorker.WorkerReportsProgress = true; // 设置可以通告进度
m_BackgroundWorker.WorkerSupportsCancellation = true; // 设置可以取消
m_BackgroundWorker.DoWork += new DoWorkEventHandler(DoWork);
m_BackgroundWorker.ProgressChanged += new ProgressChangedEventHandler(UpdateProgress);
m_BackgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(CompletedWork);
m_BackgroundWorker.RunWorkerAsync(this);
}
void DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker bw = sender as BackgroundWorker;
MainWindow win = e.Argument as MainWindow;
int i = 0;
while ( i <= 100 )
{
if (bw.CancellationPending)
{
e.Cancel = true;
break;
}
bw.ReportProgress(i++);
Thread.Sleep(1000);
}
}
void UpdateProgress(object sender, ProgressChangedEventArgs e)
{
int progress = e.ProgressPercentage;
label1.Content = string.Format("{0}",progress);
}
void CompletedWork(object sender, RunWorkerCompletedEventArgs e)
{
if ( e.Error != null)
{
MessageBox.Show("Error");
}
else if (e.Cancelled)
{
MessageBox.Show("Canceled");
}
else
{
MessageBox.Show("Completed");
}
}
private void button1_Click(object sender, RoutedEventArgs e)
{
m_BackgroundWorker.CancelAsync();
}
}
- .NET Core系列之MemoryCache 初识
- 007手机一键Root(安机网一键Root) v3.0 官方最新版 一键ROOT您的Android手机
- 12306密码被盗了怎么办?12306密码外泄解决方法
- 12个字的qq网名
- 150M迷你型无线路由器怎么设置?
- 192.168.1.1打不开怎么办?路由器192.168.1.1打不开的原因以及解决办法
- 2011年电子报合订本 电子报 编辑部 中文 PDF版 [84M]
- 2015年1月15日小米新旗舰发布会现场图文直播
- 2016.3.1vivo Xplay5新品发布会现场视频直播 优酷直播
- 2016华为P9发布会视频直播地址 4月15日华为P9国行发布会直播