[英]Threading start back again after pausing
I am using threading in my code , thread are created using function: 我在代码中使用线程,使用函数创建线程:
private void InitializeBackgoundWorkers()
{
for (int f = 0; f < maxThreads; f++)
{
listBox1.Items.Insert(0, "Starting Thread : " + (f + 1));
threadArray[f] = new BackgroundWorker();
threadArray[f].DoWork +=
new DoWorkEventHandler(backgroundWorkerFiles_DoWork);
threadArray[f].RunWorkerCompleted +=
new RunWorkerCompletedEventHandler(backgroundWorkerFiles_RunWorkerCompleted);
threadArray[f].ProgressChanged +=
new ProgressChangedEventHandler(backgroundWorkerFiles_ProgressChanged);
threadArray[f].WorkerReportsProgress = true;
threadArray[f].WorkerSupportsCancellation = true;
}
}
And the doevent is something like : 而doevent类似于:
private void backgroundWorkerFiles_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
int flag = 0;
while (rowCounter < allPostingRows.Tables[0].Rows.Count && flag == 0)
{
for (int i = 0; i < maxThreads; i++)
{
if (threadArray[i].CancellationPending == true)
{
flag = 1;
threadArray[i].CancelAsync();
worker.ReportProgress(0, "Thread Paused:");
}
}
if (flag == 0)
{
//perform work here
}
}
}
And on button i try to cancel the threads using: 在按钮上,我尝试使用以下方式取消线程:
for (int i = 0; i < maxThreads; i++)
{
threadArray[i].CancelAsync();
}
Am i cancelling the thread correctly? 我可以正确取消线程吗? As when they get canceled i see the line in listbox saying thread cancelled so it does go to the cancellation code but after some time it restarts 当他们被取消时,我看到列表框中的行说线程已取消,所以它确实进入了取消代码,但过了一段时间后重新启动
Thank you 谢谢
I don't think you really understand BackgroundWorker
. 我认为您不太了解BackgroundWorker
。 The DoWork
event handler is supposed to be a handler for one unit of work. DoWork
事件处理程序应该是一个工作单元的处理程序。 DoWork
is called with one thread. 用一个线程调用DoWork
。 It doesn't make sense to call CancelAsync
from within a DoWork
handler--that's independent of any and all other BackgroundWorker
's. 从DoWork
处理程序中调用CancelAsync
是没有意义的-它独立于任何其他所有BackgroundWorker
。 Within the DoWork
handler it should only be checking one CancellationPending
, the sender's (once cast to BackgroundWorker
, in your case worker
). 在DoWork
处理程序中,它应该只检查发送者的一个CancellationPending
(一旦强制转换为BackgroundWorker
,在您的情况是worker
)。
But, otherwise, calling CancelAsync
from the UI is the correct way to cancel a particular BackgroundWorker
. 但是,否则,从UI调用CancelAsync
是取消特定BackgroundWorker
的正确方法。
Background workers are not "thread"s. 后台工作者不是“线程”。 You''re not cancelling a thread, you're cancelling the worker--which allows the DoWork handler a chance to exit before it is done it's work. 您不是在取消线程,而是在取消工作程序,这使DoWork处理程序有机会在完成工作之前退出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.