每隔n秒唤醒线程

Dav*_*ave 2 .net c# wpf multithreading thread-safety

我正在使用C#编写WPF应用程序,我需要一些线程帮助.我有三个类,每个类需要在他们自己的线程中每n秒运行一个任务.这是我用Qt4做的方式:

class myThread : public QThread
{
    void run (void)
    {
        while (true)
        {
            mMutex.lock();
            mWaitCondition.wait (&mMutex);

            // Some task

            mMutex.unlock();
        }
    }

    void wait (int timeout)
    {
        // For shutdown purposes
        if (mMutex.tryLock (timeout))
            mMutex.unlock();
    }

    void wake (void)
    {
        mWaitCondition.wakeAll();
    }
}

// Some other class has a timer which ticks
// every n seconds calling the wake function
// of the myThread class.
Run Code Online (Sandbox Code Playgroud)

我从中获得的是受控更新间隔.因此,如果我每秒更新60次,如果代码很慢并且每秒只能运行30次,那么这样做没有问题,但它每秒运行时间不会超过60次.它也不会同时运行多次相同的代码.什么是在C#中实现这个的最简单方法?

jga*_*fin 6

你应该用一个Timer代替.

阅读这篇文章的详细信息,或这一个更紧凑的解释.