Ive been working on setting up a throttle to limit the number of messages sent. Although this works, Im curious if there is a better way? Any advice is appreciated.
public Class MyApp
{
private long _messagesSent;
private long _totalMessagesSent;
public int NumberOfMessages { get; set; }
public int MessagesPerSecond { get; set; }
public void SendMessage()
{
ThreadholdMonitor.Start();
for (var i = 0; i < NumberOfMessages; i++) {
// Code here...
if (MessagesPerSecond <= _messagesSent) {
ThreadholdMonitor.StopSendingEvent.Set();
lock (this) {
var hasPrinted = false;
while (ThreadholdMonitor.StopSendingEvent.WaitOne(0, false)) {
if (hasPrinted == false) {
Console.WriteLine("Sent " + _messagesSent + " messages");
hasPrinted = true;
}
Interlocked.Exchange(ref _messagesSent, 0);
}
}
}
SendMessage(details);
Interlocked.Increment(ref _messagesSent);
Interlocked.Increment(ref _totalMessagesSent);
}
ThreadholdMonitor.Stop();
}
}
public class ThreadholdMonitor
{
private static ManualResetEvent _monitorEvent;
public static ManualResetEvent StopSendingEvent { get; set; }
public static void Start()
{
_monitorEvent = new ManualResetEvent(false);
StopSendingEvent = new ManualResetEvent(false);
Thread monitorThread = new Thread(new ThreadStart(ControlSharedSignal));
monitorThread.Start();
}
public static void Stop()
{
_monitorEvent.Set();
}
private static void ControlSharedSignal()
{
var startTime = DateTime.Now;
while (_monitorEvent.WaitOne(0, false) == false) {
if (DateTime.Now.Subtract(startTime).Seconds >= 1) {
StopSendingEvent.Reset();
startTime = DateTime.Now;
}
}
}
}