Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is best way to fake a long running process in parallel processing?

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.

like image 272
naveen Avatar asked Feb 10 '14 13:02

naveen


2 Answers

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;
}
like image 67
Big Daddy Avatar answered Nov 03 '22 01:11

Big Daddy


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);
}
like image 39
Matthew Watson Avatar answered Nov 03 '22 02:11

Matthew Watson