Given that this is a console application, Thread.Sleep()
will actually work quite well. It blocks, but there really isn't any other work to be done while this is blocking, so there's little downsides.
If this were a GUI app, service, or other scenario where blocking is bad, however, then I would recommend using asynchronous methods, and await Task.Delay(pause)
instead, which would allow the UI to continue processing messages. This doesn't matter in a console application, though, so there is little or no downside to your current approach.
This would involve making your main method asynchrnous
static async Task PostDataMultipleTimes(int times)
{
for (int i=0;i<times;++i)
{
var sw = Stopwatch.StartNew();
PostData(); // PostData doesn't need to sleep/wait/etc anymore
var ms = (int)sw.ElapsedMilliseconds;
if (ms < 200)
await Task.Delay(200 - ms);
}
}
Note that PostData
no longer needs any logic related to blocking - it would just post your relevant data.
This would likely be possible to accomplish in .NET 4. with task continuations, but I'd likely just use Sleep
as the logic gets fairly ugly, very quickly.