问题
I am designing a 3 DOF control application for AR Drone (quad-rotor UAV) .. i am using multiple PID controllers to control the UAV .. these controllers are implemented by using dispatcher timer class .. for example at the start of the program I initialize the dispatcher timer like :
timer_yaw = new DispatcherTimer();
timer_yaw.Interval = new TimeSpan(0, 0, 0, 0, 45);
timer_yaw.Tick += new EventHandler(timer_yaw_tick);
as soon as the user presses a button on the GUI this timer is fired .
timer_yaw.Start();
in timer_yaw_tick i do a little bit of processing :
private void timer_yaw_tick(object sender, EventArgs e)
{
// drone commands and stuff ... basically a PD controller
DroneData data = droneControl.NavigationData;
PV_yaw = data.Psi;
SP_yaw = angle;
Error_yaw = SP_yaw - PV_yaw;
if (Error_yaw >= 0)
yaw_pd = 0.5f;
else if (Error_yaw < 0)
yaw_pd = -0.5f;
Derivative_yaw = (Error_yaw - PreError_yaw) / Dt_yaw;
Output_yaw = (Kp_yaw * Error_yaw) + (Kd_yaw * Derivative_yaw);
PreError_yaw = Error_yaw;
Output_yaw = Math.Round(Output_yaw, 1, MidpointRounding.AwayFromZero);
Output_yaw = Output_yaw * 1000;
t_PD_yaw = Convert.ToInt32(Output_yaw);
// this t_PD_yaw is then sent to the drone via WiFi to make required adjustment
}
Now in my application around 7 of these timers are running which are triggered at different time intervals....( the timer duration is mostly in milliseconds of all timers)
the problem i am facing is that my code runs fine sometimes but at times the application completely freezes i.e no response whatsoever .. its really making me go nuts and i can't seem to figure out the problem... am i using the correct timer for the job ???
Help would be really appreciated.. Thnx
回答1:
Most likely you are using default Dispatcher
which is related to the main UI thread and since DispatcherTimer
is connected to Default Dispatcher - you simply overloaded UI Thread Dispatcher queue by a lot of job.
One useful test - just measure how long timer_yaw_tick()
method is executed in average by putting at the start and the edn following:
// start
var watch = Stopwatch.StartNew();
// end
watch.Stop();
// see value of the watch.ElapsedMilliseconds property
I would recommend using System.Threading.Timer
class for periodic job scheduling and to dispatch UI control updates to the UI thread use Dispatcher.Invoke()
/Dispatcher.BeginInvoke()
来源:https://stackoverflow.com/questions/11826772/dispatcher-timer-freezing-the-wpf