C#.net中Backgroundworker内部的计时器 [英] Timer inside Backgroundworker in C#.net

查看:70
本文介绍了C#.net中Backgroundworker内部的计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


如何在Backgroundworker中使用Timer?请举个例子.在My Project中,我在Backgroundworker中使用了Timer.我的疑问是为什么计时器在DOWORK Event中不起作用?
问候,
Lakshmi Narayanan.S

Hi,
How to use Timer in Backgroundworker? Please give a example.In My Project , I used Timer in Backgroundworker. My Doubt is why doesn''t Timer work in DOWORK Event?
Regards,
Lakshmi Narayanan.S

推荐答案

在后台工作程序中使用计时器是毫无意义的.如果要重复执行某项操作,则应仅在backgroundworker DoWork()方法内部使用循环.这是一些粗略的代码:

Using a timer in a background worker is kinda pointless. If you want to do something repeatedly, you should just use a loop iinside the backgroundworker DoWork() method. Here''s some rough code:

private void DoWork(object sender, DoWorkEventArgs e)
{
    BackgroundWorker worker = sender as BackgroundWorker;
    int delay = 1000; // 1 second
    while (!worker.CancellationPending)
    {
        do something
        Thread.Sleep(delay);
    }
    e.Cancel = true;
}

如果您需要超过1秒的延迟,您的循环将不得不稍作更改,以使您可以tpo检测该工作程序是否已关闭:

If you need a delay longer than 1 second, your loop will have to change a little to allow you tpo detect whether or not the worker has been closed:

int delay = 1000; // 1 second
int interval = 60000;
int elapsed = 0;
while (!worker.CancellationPending)
{
    elapsed = 0;
    do something
    while (elapsed < interval && !worker.CancellationPending)
    {
        Thread.Sleep(delay);
    }
}
e.Cancel = true;


不起作用的原因是WinForms计时器在UI线程中运行,而后台工作程序在后台线程中运行.

也就是说,您不应该这样做.后台工作人员不必等待定时的时间;如果您有定时发生的事情,则可以在主线程中有一个计时器,并在激发时启动新的工作项.如果要在后台工作程序中等待输入,则可以使用阻塞的I/O调用.如果需要等待其他项目完成,请使用EventWaitHandles(手动或自动复位事件).
The reason it doesn''t work is that the WinForms timer runs in the UI thread, and background workers run in a background thread.

That said, you shouldn''t be doing it. A background worker shouldn''t need to wait for timed periods; if you have something that happens at timed intervals, you can have a timer in the main thread and start new work items when it fires. If you want to wait for input in a background worker, you can use a blocking I/O call. If it needs to wait for some other item to be complete, use EventWaitHandles (Manual- or AutoResetEvents).


这篇关于C#.net中Backgroundworker内部的计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆