[英]C# Background Worker Question
我有一個后台工作人員,它基本上執行以下操作:
當有文件要處理時,上述步驟將需要循環並繼續處理。
我希望后台工作人員能夠停止,並且我看到了 WorkerSupportsCancellation 設置,但我如何確保它只能在文件之間停止,而不是在處理文件時停止?
將WorkerSupportsCancellation
設置為 true,並定期檢查DoWork
事件處理程序中的CancellationPending
屬性。
CancelAsync
方法僅設置CancellationPending
屬性。 它不會殺死線程; 由工人來響應取消請求。
例如:
private void myBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
while( !myBackgroundWorker.CancellationPending )
{
// Process another file
}
}
您必須在文件處理結束時檢查后台工作人員的 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;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.