c#BackgroundWorker取消问题 [英] c# BackgroundWorker cancelling problem
问题描述
我正在起诉backgroundworker做一些耗时的工作,如果我不想等待很长时间才完成,我想取消它.
在我的一份工作中,我可以定期检查CancellationPending,因为我将它放入for语句中,但在循环中,但是还有另一种情况.
假设我要从系统中获取大量数据.在这种情况下,我无法定期检查CancellationPending.
假设dowork在很长一段时间内都无法完成工作,那么如何取消线程?
I am suing backgroundworker do some time consuming work and I want to cancel it if I don''t want to wait long time until it finish.
in one of my dowork I can check the CancelationPending periodically, since I put it in for statement where in loop, but there is another situation.
let''s say that I am going after a large amount of data from our system. In this case I can''t periodically check CancelationPending.
Assuming the dowork is off doing its job for a very long time, how do you cancel the thread?
推荐答案
您不能强制终止后台工作程序,它根本不是为此目的而设计的.
您有3个选项,按照我使用它们的顺序.
1)如果使用.NET 4.0,则可以使用TPL,Sacha Barber撰写了有关该主题的一系列文章.
任务并行库:n之1 [线程教程(X#) [
You can''t force the termination of a background worker, it simply isn''t designed for that.
You have 3 options, in the order in which I would use them.
1) If you use .NET 4.0 you can use the TPL, Sacha Barber has written a series of articles on the subject.
Task Parallel Library: 1 of n[^]
2) You can use the good old System.Threading.Thread
Threading Tutorial (X#)[^]
3) You can get the get the Thread the BackgroundWorker is running on in the DoWork event save it in a field and you can then abort the thread.
private Thread _backgroundWorkerThread;
public void StartBackgroundWorker()
{
BackgroundWorker backgroundWorker = new BackgroundWorker();
backgroundWorker.DoWork += DoWork;
backgroundWorker.RunWorkerAsync();
}
public void AbortBackgroundWorker()
{
if(_backgroundWorkerThread != null)
_backgroundWorkerThread.Abort();
}
void DoWork(object sender, DoWorkEventArgs e)
{
try
{
_backgroundWorkerThread = Thread.CurrentThread;
// Do your work...
}
catch(ThreadAbortException)
{
// Do your clean up here.
}
}
这篇关于c#BackgroundWorker取消问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!