我有一个功能,我想每1秒运行一次,除此之外我还有其他东西, 因为我在我的其他功能上使用Thread并避免Window Crashes我决定使用Backgroundworker来调用假设运行的函数:
Main()
{
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += new DoWorkEventHandler(worker_DoWork);
worker.RunWorkerAsync();
}
public void worker_DoWork(object sender, EventArgs e)
{
AutoChecking(); // thats a function should Run on Background every 1 second
}
public void AutoChecking()
{
this.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
{
if (SystemisGood == true)
Updatecolor.Fill = Green;
else
Updatecolor.Fill = Red;
}));
}
然而,这个功能现在只运行一次任何理由或解决方案,让它每隔一秒工作一次并留在后台工作者? P.S:我不想使用Timer ......
答案 0 :(得分:1)
不使用定时器是浪费的,因为它们非常轻量级并且只发送定期消息,但是您可以通过使用低开销轮询循环并检查时间来完成您想要的任务,就像通过定时器代码本身。例如:
Main()
{
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += new DoWorkEventHandler(worker_DoWork);
worker.RunWorkerAsync();
}
bool exitBGThread = false;
public void worker_DoWork(object sender, EventArgs e)
{
TimeSpan interval = new TimeSpan(0, 0, 1);
while (!exitBGThread)
{
DateTime start = DateTime.Now;
AutoChecking(); // thats a function should Run on Background every 1 second
while (!exitBGThread)
{
DateTime cur = DateTime.Now;
if (cur - start >= interval)
break;
Thread.Sleep(100);
}
}
}
public void AutoChecking()
{
this.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
{
if (SystemisGood == true )
Updatecolor.Fill = Green;
else
Updatecolor.Fill = Red;
}));
}
如果你真的使用了exitBGThread,你会想要使用lock {},这有点简化了,但你明白了。