在Backgroundworker中停止Dowork [英] Stoping Dowork in Backgroundworker

查看:100
本文介绍了在Backgroundworker中停止Dowork的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用backgroundworker的dowork方法连接到我的数据库.
花了几分钟.
我想要按取消"按钮,此过程停止运行.

i connect to my database in dowork method''s of backgroundworker.
it''s take a few minutes .
i want by pressing cancel button,this process stoped running.
How do this?

推荐答案

您必须自己实现大部分取消代码,但是您还需要在后台工作人员本身上启用一些功能.
必须设置WorkerSupportsCancellation属性.
然后,当您要取消时,调用CancelAsync,这样做会将backgroundworker的cancelpending属性设置为true.
您必须定期检查此属性,以检查用户是否请求取消,如果您不执行此操作,那么它将继续运行.

You have to implement most of the cancellation code yourself, but there are a few things you have to enable on the backgroundworker itself.
The WorkerSupportsCancellation property must be set.
Then when you want to cancel, you call CancelAsync, doing this sets the cancellationpending property of the backgroundworker to true.
You have to check this property at regular intervals to check if the user requested the cancel, if you don''t do this, well, it will keep on running.

private void workerDoWork(object sender, DoWorkEventArgs e)
{
  for(int i = 0;i<1000000;i++){
    TimeConsumingMethod();
    if (myworker.CancellationPending){
      e.Cancel = true;
      return;
    }
  }
}

private void btnCancel_Click(object sender,RoutedEventArgs e)
{
  myWorker.CancelAsync();
}


这篇关于在Backgroundworker中停止Dowork的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆