How can i use a BackgroundWorker with a timer tick?

后端 未结 6 739
一向
一向 2020-12-06 04:10

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

Added a backgroundworker. Added a Shown event the Shown event fire after all the constructor have been loaded.

6条回答
  •  渐次进展
    2020-12-06 04:16

    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);
        }
    

提交回复
热议问题