Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/303.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 我如何使用带有计时器刻度的BackgroundWorker?_C#_Multithreading_Timer - Fatal编程技术网

C# 我如何使用带有计时器刻度的BackgroundWorker?

C# 我如何使用带有计时器刻度的BackgroundWorker?,c#,multithreading,timer,C#,Multithreading,Timer,决定不使用任何计时器。 我所做的更简单 添加了一个后台工作人员。 在加载所有构造函数后,在显示事件中添加了显示事件。 在显示的事件中,我异步启动backgroundworker 在后台工作中,我正在做: private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { while(true) { cpuView();

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

添加了一个后台工作人员。 在加载所有构造函数后,在显示事件中添加了显示事件。 在显示的事件中,我异步启动backgroundworker

在后台工作中,我正在做:

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

你不能把这段代码扔进后台工作程序,然后期望它工作。任何更新UI元素(标签、文本框等)的内容都需要在主线程上调用。您需要分解逻辑以获取数据和更新UI的逻辑

我想说,你最好的办法是这样做:

在timer Tick()方法中:

在后台worker DoWork()方法中:

在后台工作程序Completed()方法中:


首先,确保你的头脑在多线程和它的问题(特别是用户界面的东西)周围

然后你可以用像这样的方式思考

public class Program
{
    public static void Main(string[] args)
    {
        Timer myTimer = new Timer(TimerTick, // the callback function
            new object(), // some parameter to pass
            0, // the time to wait before the timer starts it's first tick
            1000); // the tick intervall
    }

    private static void TimerTick(object state)
    {
        // less then .NET 4.0
        Thread newThread = new Thread(CallTheBackgroundFunctions);
        newThread.Start();

        // .NET 4.0 or higher
        Task.Factory.StartNew(CallTheBackgroundFunctions);
    }

    private static void CallTheBackgroundFunctions()
    {
        cpuView();
        gpuView();
    }
}

请记住(就像告诉您的那样)您的
cpuView()
gpuView()
将无法正常工作。

在这种情况下,最好使用两个线程并在这两个线程中执行cpu密集型操作。请注意,您必须使用访问控制。您可以将这些访问封装到properties setter中,或者更好地将它们拉到视图模型类中

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
太复杂了;使用
定时器
很难实现有保证的停止

我建议您使用worker
Thread
和循环,循环等待取消
ManualResetEvent
以获得所需的时间间隔:

  • 如果设置了取消事件,则工作进程退出循环
  • 如果存在超时(您需要的时间间隔超过),则执行系统监视
以下是代码的草案版本。请注意,我还没有测试过它,但它可以告诉你这个想法

public class HardwareMonitor
{
    private readonly object _locker = new object();
    private readonly TimeSpan _monitoringInterval;
    private readonly Thread _thread;
    private readonly ManualResetEvent _stoppingEvent = new ManualResetEvent(false);
    private readonly ManualResetEvent _stoppedEvent = new ManualResetEvent(false);

    public HardwareMonitor(TimeSpan monitoringInterval)
    {
        _monitoringInterval = monitoringInterval;
        _thread = new Thread(ThreadFunc)
            {
                IsBackground = true
            };
    }

    public void Start()
    {
        lock (_locker)
        {
            if (!_stoppedEvent.WaitOne(0))
                throw new InvalidOperationException("Already running");

            _stoppingEvent.Reset();
            _stoppedEvent.Reset();
            _thread.Start();
        }
    }

    public void Stop()
    {
        lock (_locker)
        {
            _stoppingEvent.Set();
        }
        _stoppedEvent.WaitOne();
    }

    private void ThreadFunc()
    {
        try
        {
            while (true)
            {
                // Wait for time interval or cancellation event.
                if (_stoppingEvent.WaitOne(_monitoringInterval))
                    break;

                // Monitoring...
                // NOTE: update UI elements using Invoke()/BeginInvoke() if required.
            }
        }
        finally
        {
            _stoppedEvent.Set();
        }
    }
}
是的,你可以:

在计时器滴答声事件中:

private void timer_Tick(object sender, EventArgs e)
{

  timer.Enabled = false;

  backgroundworker.RunWorkerAsync();

  timer.Enabled = true;
}
在您的Backgroundworker嫁妆活动中:

private void backgroundworker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
   try
   {
       //Write what you want to do
   }
   catch (Exception ex)
   {
       MessageBox.Show("Error:\n\n" + ex.Message, "System", MessageBoxButtons.OK, MessageBoxIcon.Error);
   }
}

在我的例子中,我在WinForm应用程序中使用了BackgroundWorkerSystem.Timers.TimerProgressBar。我遇到的是,在第二个勾号上,我将重复BackgroundWorker的Do Work,在尝试更新BackgroundWorker的ProgressChanged中的ProgressBar时,我遇到了一个交叉线程异常。然后我在SO@Rudedog2上找到了一个解决方案,该解决方案说明当您初始化Timer.Timer对象以用于Windows窗体中,必须将计时器实例的SynchronizingObject属性设置为窗体

systemTimersTimerInstance.SynchronizingObject = this; // this = form instance.

idalonzo Dispose(bool disposing)有问题,我收到错误消息说:错误1类型“HardwareMonitoring.Form1”已使用相同的参数类型定义了名为“Dispose”的成员,另一个Dispose函数在Form1.Designer.cs中
private void timer_Tick(object sender, EventArgs e)
{

  timer.Enabled = false;

  backgroundworker.RunWorkerAsync();

  timer.Enabled = true;
}
private void backgroundworker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
   try
   {
       //Write what you want to do
   }
   catch (Exception ex)
   {
       MessageBox.Show("Error:\n\n" + ex.Message, "System", MessageBoxButtons.OK, MessageBoxIcon.Error);
   }
}
systemTimersTimerInstance.SynchronizingObject = this; // this = form instance.