如何使用带有计时器刻度的 BackgroundWorker? [英] How can i use a BackgroundWorker with a timer tick?

查看:12
本文介绍了如何使用带有计时器刻度的 BackgroundWorker?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

决定不使用任何计时器.我做的更简单.

Decided to not use any timers. What i did is simpler.

添加了后台工作人员.添加了 Shown 事件,Shown 事件在所有构造函数加载后触发.在 Shown 事件中,我正在启动后台工作器异步.

Added a backgroundworker. Added a Shown event the Shown event fire after all the constructor have been loaded. In the Shown event im starting the backgroundworker async.

在我正在做的后台工作 DoWork 中:

In the backgroundworker DoWork im doing:

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            while(true)
            {
                cpuView();
                gpuView();
                Thread.Sleep(1000);
            }
        }

推荐答案

在这种情况下,最好使用两个 System.Threading.Timer 并在这两个线程中执行 CPU 密集型操作.请注意,您必须使用 BeginInvoke.您可以将这些访问封装到属性 setter 中,甚至更好地将它们提取到视图模型类中.

In this case it's better to use two System.Threading.Timer and execute your cpu-intensive operations in these two threads. Please note that you must access controls with BeginInvoke. You can encapsulate those accesses into properties setter or even better pull them out to a view model class.

public class MyForm : Form
{
    private System.Threading.Timer gpuUpdateTimer;
    private System.Threading.Timer cpuUpdateTimer;

    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);

        if (!DesignMode)
        {
            gpuUpdateTimer = new System.Threading.Timer(UpdateGpuView, null, 0, 1000);
            cpuUpdateTimer = new System.Threading.Timer(UpdateCpuView, null, 0, 100);
        }
    }

    private string GpuText
    {
        set
        {
            if (InvokeRequired)
            {
                BeginInvoke(new Action(() => gpuLabel.Text = value), null);
            }
        }
    }

    private string TemperatureLabel
    {
        set
        {
            if (InvokeRequired)
            {
                BeginInvoke(new Action(() => temperatureLabel.Text = value), null);
            }
        }
    }

    private void UpdateCpuView(object state)
    {
        // do your stuff here
        // 
        // do not access control directly, use BeginInvoke!
        TemperatureLabel = sensor.Value.ToString() + "c" // whatever
    }

    private void UpdateGpuView(object state)
    {
        // do your stuff here
        // 
        // do not access control directly, use BeginInvoke!
        GpuText = sensor.Value.ToString() + "c";  // whatever
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            if (cpuTimer != null)
            {
                cpuTimer.Dispose();
            }
            if (gpuTimer != null)
            {
                gpuTimer.Dispose();
            }
        }

        base.Dispose(disposing);
    }

这篇关于如何使用带有计时器刻度的 BackgroundWorker?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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