每n秒唤醒一次线程
问题描述:
我在写一个使用C#的WPF应用程序,我需要一些线程帮助。我有三个类,每个类都需要在他们自己的线程中每隔n秒运行一次任务。这是我用Qt4做的:每n秒唤醒一次线程
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.
我从中得到的是一个受控更新间隔。所以如果我每秒更新60次,如果代码很慢并且每秒只能运行30次,那么这样做没有问题,但是它每秒不会超过60次。它也不会同时运行相同的代码。什么是在C#中实现这个最简单的方法?
答
您可以使用有类在给定的时间运行的任务做
using System;
using System.Timers;
using System.Threading;
public class ClassTask
{
System.Timers.Timer timer = null;
public bool IsRunning { get; set; }
public DateTime LastRunTime { get; set; }
public bool IsLastRunSuccessful { get; set; }
public double Interval { get; set; }
public bool Stopped { get; set; }
public ClassTask(double interval)
{
this.Interval = interval;
this.Stopped = false;
timer = new System.Timers.Timer(this.Interval);
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
timer.Enabled = true;
}
public void Start()
{
this.Stopped = false;
this.StartTask();
}
public void Stop()
{
this.Stopped = true;
}
private void StartTask()
{
if (!this.Stopped)
{
//Thread thread = new Thread(new ThreadStart(Execute));
//thread.Start();
Execute();
}
}
private void Execute()
{
try
{
this.IsRunning = true;
this.LastRunTime = DateTime.Now;
// Write code here
this.IsLastRunSuccessful = true;
}
catch
{
this.IsLastRunSuccessful = false;
}
finally
{
this.IsRunning = false;
}
}
void timer_Elapsed(object sender, ElapsedEventArgs e)
{
if (!this.IsRunning)
StartTask();
}
}
using System;
using System.Data;
using System.Configuration;
public class ClassTaskScheduler
{
ClassTask task = null;
public ClassTaskScheduler()
{
this.task = new ClassTask(60000);
}
public void StartTask()
{
this.task.Start();
}
public void StopTask()
{
this.task.Stop();
}
}
在Global.asax中或要调用此
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
ClassTaskScheduler _scheduler = new ClassTaskScheduler();
_scheduler.StartTask();
}
void Application_End(object sender, EventArgs e)
{
// Code that runs on application shutdown
ClassTaskScheduler _scheduler = new ClassTaskScheduler();
_scheduler.StopTask();
}
您可以使用EXECUTE()函数间隔....
答
.NET中的等价物将使用ManualResetEvent
。使用带有超时的WaitOne
方法来引起等待。它也可以兼作关机机制。这种方法的好处是很简单,一切运行一个线程,并且相同的代码不能并行执行(因为它全部在一个线程上)。
class myThread
{
private ManualResetEvent m_WaitHandle = new ManualResetEvent(false);
public myThread
{
new Thread(Run).Start();
}
public void Shutdown()
{
m_WaitHandle.Set(); // Signal the wait handle.
}
private void Run()
{
while (!m_WaitHandle.WaitOne(INTERVAL)) // The waiting happens here.
{
// Some task
}
// If execution gets here then the wait handle was signaled from the Shutdown method.
}
}
这实际上很好知道以后,谢谢! – Dave 2011-05-19 08:55:26