Sha*_*ant 8 c# backgroundworker
我有一个后台工作者基本上执行以下操作:
在有待处理的文件时,上述步骤需要循环并继续处理.
我希望后台工作者能够被停止,我看到了WorkerSupportsCancellation设置,但是如何确保它只能在文件之间停止,而不是在处理文件时?
设置WorkerSupportsCancellation为true,并定期检查事件处理程序中的CancellationPending属性DoWork.
该CancelAsync方法仅设置CancellationPending属性.它不会杀死线程; 由工作人员来回应取消请求.
例如:
private void myBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
while( !myBackgroundWorker.CancellationPending )
{
// Process another file
}
}
Run Code Online (Sandbox Code Playgroud)
小智 5
您必须在文件处理结束时检查后台工作程序的CancellationPending procepty
static void Main(string[] args)
{
BackgroundWorker bw = new BackgroundWorker();
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.WorkerSupportsCancellation = true;
bw.RunWorkerAsync();
Thread.Sleep(5000);
bw.CancelAsync();
Console.ReadLine();
}
static void bw_DoWork(object sender, DoWorkEventArgs e)
{
string[] files = new string[] {"", "" };
foreach (string file in files)
{
if(((BackgroundWorker)sender).CancellationPending)
{
e.Cancel = true;
//set this code at the end of file processing
return;
}
}
}
Run Code Online (Sandbox Code Playgroud)