I have a progress bar on the front-end of my web app which gets its current percentage by listening for messages sent from a SignalR hub in the back-end. It tracks a long running process which has several stages with many iterations.
My initial set-up was to simply send a message every iteration. This caused issues however as the rate of iteration (and therefore message rate) was too fast for the front-end and the bar became very jumpy and buggy.
So instead I decided to use a Stopwatch object in the following way (where SendProgress() is the procedure that tells the hub to message the client):
int progressCount = 1;
var stopWatch = new System.Diagnostics.Stopwatch();
stopWatch.Start();
for(int i=0; i<taskCount; i++)
{
//PROCESS DONE HERE
if (stopWatch.Elapsed.TotalMilliseconds >= 500.0)
{
SendProgress(taskCount, progressCount, 0, 40);
stopWatch.Reset();
stopWatch.Start();
}
progressCount++;
}
Thus preventing messages from being sent faster than once every 500ms.
This worked well in terms of limiting the message rate, however I noticed a drop in performance, which after a little research I gather is due to using Stopwatch, which is inefficient.
What would be a better approach here? I also though of using Thread.Sleep() but that would just be adding artificial slowness to the algorithm which is, obviously, bad. Is there a way I can accurately control the message rate, without slowing things down too badly?