取消后台工作人员内长期运行过程的最佳方法
什么是快速取消背景工人内长期运行过程的最佳解决方案? 例如,我们有这样的情况:
private void DoWork(object sender, DoWorkEventArgs e)
{
...
for (int i = 0; i < items; i++)
{
if (_worker.CancellationPending == true)
{
e.Cancel = true;
break;
}
else
{
VeryLongRunningProcess();
}
}
}
private void VeryLongRunningProcess()
{
var a = Test();
var b = Test2();
Thread.Sleep(5000);
var c = Test3();
}
在这种情况下,在他完成身体内部的所有东西之前,将在按下取消时尚未完成。
在这种情况下该怎么办?
我试图将(背景工)发件人作为param和内部的loverlongrunnunnunnunningprocess()和在此方法中检查取消限额,但我不知道这种正确的方式是正确的
What is the best solution to quickly cancel long running processes inside background worker?
For example, we have such situation:
private void DoWork(object sender, DoWorkEventArgs e)
{
...
for (int i = 0; i < items; i++)
{
if (_worker.CancellationPending == true)
{
e.Cancel = true;
break;
}
else
{
VeryLongRunningProcess();
}
}
}
private void VeryLongRunningProcess()
{
var a = Test();
var b = Test2();
Thread.Sleep(5000);
var c = Test3();
}
In such case, VeryLongRunningProcess() will be not finished on pressing cancel until he finished everything inside his body.
What to do in such cases?
I tried to pass (BackgroundWorker)sender to VeryLongRunningProcess() as param and inside this method check for CancellationPending, but i dont know is this correct way or not
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果问题与工人之类的课程隔离开来,您可以将func用作参数,并在方法外部使用方法,则可以检查您的
方法内部的访问权限,您可以检查是否必须尽可能多地取消操作。您可以将func用作其他方法中的参数,例如Test1,test2 ...如果其中任何一个需要很长时间才能完成。
然后,您以这种形式调用您的方法:
正如其他人评论的那样,可能有趣的是异步/等待。
Update
如果您想选择取消的使用或不选择使用:
If the problem is isolated your VeryLongRunningProcess from classes like the worker, you can use a Func as a parameter and leave outside your method the worker access
Inside your method, you may check if you must cancel the operation as many times you need. And you can use the Func as a parameter in other methods like Test1, Test2... if any of them takes long time to finish.
Then, you invoke your method in this form:
As other people comment, maybe interesting use async/await.
UPDATE
Another way to do if you want choose the use or not of the cancellation:
通常,您应该将长期运行的过程作为“ async”方法(公共异步任务或任务dowork()),以进行资源破坏。 “ CancelationToken”可以在线程,线程池工作项目之间取消合作取消。同样,可以传播一个可以调用的回调委托,该回调委托被取消或函数是compleete时可以调用的。
Normally you should create long-running process as "async" method (public async Task or Task DoWork()) for resources destribution purposes. "CancelationToken" enables cooperative cancellation between threads, thread pool work items. Also it is possible to propagate a callback delegate that can be invoked when Cancellation Token cancelled or function is compleete.