Lucy Copp Lucy Copp - 11 months ago 63
C# Question

Events not occurring at correct time interval c# timers

I am writing a program which sends and recieves messages to another application.
Some messages have to be sent at certain intervals. For example, I have four messages which get sent, one should be sent every 8 seconds, two are to be sent every 0.5 seconds and one should be sent every 1 second.

The messages seem to be sending fine, however they are all sending at the same time. I used a timestamp to determine that they all seem to be sent every 11 seconds. Below is the code I have implimented:

Here are where the timers are declared:

System.Timers.Timer statusTimer = new System.Timers.Timer(1000);
System.Timers.Timer heightTimer = new System.Timers.Timer(500);
System.Timers.Timer keepAliveTimer = new System.Timers.Timer(8000);
System.Timers.Timer longHeightTimer = new System.Timers.Timer(500);


And here in the main window they are started (this is a WPF project):

statusTimer.Start();
heightTimer.Start();
keepAliveTimer.Start();
longHeightTimer.Start();

statusTimer.Elapsed += delegate { sendStatusMessage(); };
heightTimer.Elapsed += delegate { sendHeightMessage(); };
keepAliveTimer.Elapsed += delegate { sendKeepAliveMessage(); };
longHeightTimer.Elapsed += delegate { sendLongWarpMessage(); };


Here is an example of a method which is should be fired when the time is elapsed (there is not much point in showing them all as they are all basically the same):

public void sendStatusMessage()
{
sendMessage(status_msg.TranslateToMessage());
Dispatcher.Invoke(DispatcherPriority.Normal, (System.Action)delegate //change the priority so you can use UI
{
statusMsgLbl.Content = "Status Msg Sent: " + DateTime.Now.ToLongTimeString();
});

}


And finally this the method which sends the message, as bytes, to the other application using a network stream:

public void sendMessage(byte[] toSend)
{
try
{
lock (NSLock)
{
for (int i = 0; i < toSend.Length; i++)
{
nwStream.WriteByte(toSend[i]);
nwStream.Flush();
}
}
}
catch { MessageBox.Show("Unable to send message"); }
}

Answer Source

You may try to use a DispatcherTimer with an async Tick event handler:

DispatcherTimer statusTimer = new DispatcherTimer
{
    Interval = TimeSpan.FromSeconds(1.0)
};

...

statusTimer.Tick += async (s, e) =>
{
    var message = status_msg.TranslateToMessage());

    await nwStream.WriteAsync(message, 0, message.Length);

    statusMsgLbl.Content = "Status Msg Sent: " + DateTime.Now.ToLongTimeString();
};

statusTimer.Start();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download