-4

我有一个函数,我想每 1 秒运行一次,除此之外我还有其他东西,因为我在我的其他函数上使用 Thread 并避免窗口崩溃我决定使用 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;
    }));
}

然而,这个功能现在只能工作一次,任何理由或解决方案让它每秒钟工作一次并留在后台工作人员?!PS:我不想用定时器...

4

1 回答 1

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 { },但您明白了。

于 2013-02-06T04:02:51.757 回答