如何启动和停止连续运行的背景工人用一个按钮 [英] How To Start And Stop A Continuously Running Background Worker Using A Button
问题描述
让我们说我有一个后台工作是这样的:
私人无效backgroundWorker1_DoWork(对象发件人,DoWorkEventArgs E)
{
而(真)
{
//杀僵尸
}
}
我怎样才能让这个后台工作启动和停止使用一个WinForm一个按钮?
私人布尔_performKilling;私人无效backgroundWorker1_DoWork(对象发件人,DoWorkEventArgs E)
{
而(真)
{
如果(_performKilling)
{
//杀僵尸
}
}
}私人无效StartKilling()
{
_performKilling = TRUE;
}私人无效StopAllThatKilling()
{
_performKilling = FALSE;
}
现在叫 StartKilling
和 StopAllThatKilling
从按钮单击处理程序或其他任何适当的位置。
您的可能的开始担心这里线程安全的,因为该 _performKilling
字段更新,并在不同的线程访问。然而,在访问(和更新)一布尔
是一个原子操作,所以应该不需要额外的锁定机制。
更新结果
继原子周围的讨论,数据和访问顺序的新鲜度,这里是一个更新code样品,将通过增加周围的所有的锁解决这些问题的读写标志的操作:
私人布尔_performKilling;
私有对象_lock =新的对象();私人无效backgroundWorker1_DoWork(对象发件人,DoWorkEventArgs E)
{
而(真)
{
布尔runLoop;
锁(_lock)
{
runLoop = _performKilling;
}
如果(runLoop)
{
//杀僵尸
}
}
}私人无效StartKilling()
{
锁(_lock)
{
_performKilling = TRUE;
}
}私人无效StopAllThatKilling()
{
锁(_lock)
{
_performKilling = FALSE;
}
}
Let's say I have a background worker like this:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
while(true)
{
//Kill zombies
}
}
How can I make this background worker start and stop using a button on a WinForm?
private bool _performKilling;
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
while(true)
{
if (_performKilling)
{
//Kill zombies
}
}
}
private void StartKilling()
{
_performKilling = true;
}
private void StopAllThatKilling()
{
_performKilling = false;
}
Now call StartKilling
and StopAllThatKilling
from a button click handler or any other appropriate location.
You could start to worry about thread safety here, given that the _performKilling
field is updated and accessed on different threads. However, accessing (and updating) a bool
is an atomic operation, so it should require no extra locking mechanisms.
Update
Following the discussion around atomicity, freshness of data and order of access, here is an updated code sample that will address those issues by adding a lock around all read and write operations of the flag:
private bool _performKilling;
private object _lock = new object();
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
while(true)
{
bool runLoop;
lock (_lock)
{
runLoop = _performKilling;
}
if (runLoop)
{
//Kill zombies
}
}
}
private void StartKilling()
{
lock (_lock)
{
_performKilling = true;
}
}
private void StopAllThatKilling()
{
lock (_lock)
{
_performKilling = false;
}
}
这篇关于如何启动和停止连续运行的背景工人用一个按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!