0

Question is about using a timer in each created thread.

I’m writing an application which collects a CPU data from a PC every 30 seconds. It works if I collect data only from 1 PC and using 1 timer, without any thread. Now, I want to collect data from 2 PCs simultaneously. To this end, I decided to use threading where each thread will work for each PC and will have its own timer. So, 2 threads with 2 timers for 2 PCs. I use System.Windows.Threading.DispatcherTimer to create a timer by each thread. But, the issue is that the created timer doesn't start working (i.e. doesn't call timerTick). Hence, if I create a timer without threads, then it works correctly, whereas a thread created timer doesn't work. :(

Maybe the considered solution is not correct and need some changes. Please, help me to understand the problem.

Here is a simple version of the code:

void CreateThread()
{
    Thread First = new Thread(new ThreadStart(FirstThreadWork));
    First.Start();
}

private void FirstThreadWork()
{
    System.Windows.Threading.DispatcherTimer timer;

    timer = new System.Windows.Threading.DispatcherTimer();

    timer.Tick += new EventHandler(timerTick);
    timer.Interval = new TimeSpan(0, 0, 30);
    timer.Start();
}

private void timerTick(object sender, EventArgs e)
{
    MessageBox.Show("Show some data");
}
4

1 回答 1

2

DispatcherTimer仅当它是在 UI 线程上创建而不是在后台线程上创建时才有效。如果您不打算在您的timerTick方法中操作任何 UI 元素,那么您可能需要考虑System.Timers.Timer

可以在@this blog post找到关于.net中所有可用计时器的详细讨论

示例代码

    void StartTimer()
    {
        var timer = new System.Timers.Timer();

        timer.Elapsed += timerTick;
        timer.Interval = 30000;
        timer.Enabled = true;
        timer.Start();

    }

    private void timerTick(object sender, EventArgs e)
    {
        MessageBox.Show("Show some data");
    }
于 2013-08-12T13:33:26.100 回答