C# 停止 BackgroundWorker

标签 c# .net multithreading loops backgroundworker

我对 backgroundworker 有疑问。

我在 backgroundworker 中有无限循环。我该如何阻止它?

最佳答案

改成非无限循环

BackgroundWorker 内置了对取消的支持。取消后台 worker 调用 BackgroundWorker.CancelAsync .您还需要修改工作人员代码以检查文档中提到的取消:

CancelAsync submits a request to terminate the pending background operation and sets the CancellationPending property to true.

When you call CancelAsync, your worker method has an opportunity to stop its execution and exit. The worker code should periodically check the CancellationPending property to see if it has been set to true.

例如,如果您的工作线程中有这个无限循环:

while (true)
{
    ...
}

那么你可以把它改成:

while (!backgroundWorker.CancellationPending)
{
    ...
}

要使取消生效,您还需要设置属性 BackgroundWorker.WorkerSupportsCancellationtrue。这可以在设计器中完成。

关于C# 停止 BackgroundWorker,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4618415/

相关文章:

c# - 使用 Windows 安全连接到 WCF 服务时出错

.NET 路径操作库

ios - 如何在 iOS 编程中保持方法执行的顺序?

c# - 使用 DataAdapter 填充表

c# - 使用 XmlSerializer 反序列化具有选择的复杂类型元素

c# - 在 C# 4 中,如何在具有重载构造函数的父类的子类中拥有带可选参数的构造函数?

java - 我需要澄清 ThreadpoolExecutor beforeExecute 和 afterExecute Hook

java - 在 Thread 上调用 interrupt(),但它从未被中断

c# - 如何在 C# 中删除空格后的尾随字符?

c# - 通过 ASP.NET 将 PRIMARY Key 值插入 SQL 而不复制 CHAR