[英]C# How to stop running backgroundWorker without cancellationPending
is there any way to stop backgroundWorker thread without cancellationPending? 有什么方法可以在没有cancelPending的情况下停止backgroundWorker线程? I have code like this:
我有这样的代码:
DoWorkFunction
{
if(worker.cancellationPending == true) return; //this works great but
VeryLongTimeComputingFunc();//this function take a lot of time and if it starts i can't stop it with cancellationPending
...Do something
}
Is there any way to stop worker even if it started VeryLongTimeComputingFunc()? 即使启动了VeryLongTimeComputingFunc(),有什么方法可以阻止它吗?
Maybe you could fire an "CancelWorker" event in your "VeryLongTimeComputingFunc" and in the EventHandler you stop the BackgroundWorker with "worker.CancelAsync()". 也许您可以在“ VeryLongTimeComputingFunc”中触发“ CancelWorker”事件,然后在EventHandler中使用“ worker.CancelAsync()”停止BackgroundWorker。
This should work: 这应该工作:
class BackgroundClass
{
public event EventHandler CancelWorker;
BackgroundWorker worker = new BackgroundWorker();
BackgroundClass()
{
CancelWorker += new EventHandler(BackgroundClass_CancelWorker);
}
void BackgroundClass_CancelWorker(object sender, EventArgs e)
{
worker.CancelAsync();
}
void RunBackgroundWorker()
{
worker.DoWork += (sender, args) =>
{
VeryLongTimeComputingFunction();
};
}
void VeryLongTimeComputingFunction()
{
if (CancelWorker != null)
{
CancelWorker(this, new EventArgs());
}
}
}
This would require that you can change something in the "VeryLongTimeComputingFunction()" 这将要求您可以在“ VeryLongTimeComputingFunction()”中进行更改。
Assuming you can not add proper cancellation support inside VeryLongTimeComputingFunction
, your best option is to save a reference to the BGW's thread and call Abort
on it. 假设您不能在
VeryLongTimeComputingFunction
添加适当的取消支持,则最好的选择是保存对BGW线程的引用并在其上调用Abort
。 Keep in mind this is not generally recommended as it may involve a messy cleanup. 请记住,一般不建议这样做,因为它可能涉及到混乱的清理工作。
To be safe, you should catch any ThreadAbortedException
raised in your long function. 为了安全起见,您应该捕获long函数中引发的任何
ThreadAbortedException
。
private Thread bgThread;
void DoWorkFunction()
{
bgThread = Thread.CurrentThread;
try
{
VeryLongTimeComputingFunc();
}
catch (ThreadAbortedException e)
{
//do any necessary cleanup work.
bgThread = null;
}
}
void CancelBGW()
{
if (bgThread != null)
{
bgThread.Abort();
}
}
Depending on when and how CancelBGW
is called, you may also need a lock
around assignments of bgThread
. 根据何时以及如何
CancelBGW
叫,你可能还需要一个lock
周围的分配bgThread
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.