I was wondering what is the best way to fake a long running task when multiple tasks are being run in parallel. First thing that comes on mind is Thread.Sleep
public void FakeLongRunningTask()
{
Thread.Sleep(5000);
}
However problem with above code is that calling Thread.Sleep will block this thread which means it will give up it's processor time slice, so calling a method with Thread.Sleep in a parallel environment is as good as not calling it at all. So if I'm running three tasks in parallel and One of which is calling Thread.Sleep, then this task will have no effect on performance (though It might force CLR to generate more threads !!!). But what i want is to fake a task which would effect the overall performance.
Using the 4.5 framework, I think you can use Task.Delay
EDIT: In response to a request. Here's an untested sample:
async Task LongRunningOperation()
{
await Task.Delay(5000);
}
private async void SomeEvent(object sender, EventArgs e)
{
await LongRunningOperation();
}
2nd EDIT: Using the 4.0 framework, this may work (untested):
Task Delay(int interval)
{
var z = new TaskCompletionSource<object>();
new Timer(_ => z.SetResult(null)).Change(interval, -1);
return z.Task;
}
If you want a busy wait which will keep one core of the processor occupied, you could try something like this:
public void BusyWait(int milliseconds)
{
var sw = Stopwatch.StartNew();
while (sw.ElapsedMilliseconds < milliseconds)
Thread.SpinWait(1000);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With