简体   繁体   中英

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.

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);
}

You almost did it:

public async Task FakeLongRunningTask()
{
    await Task.StartNew(() => Thread.Sleep(5000));
}

and usage in some event (sorry, Big Daddy =D):

private async void SomeEvent(object sender, EventArgs e)
{
    await FakeLongRunningTask();
}

Notice, what you have to use it with await (which required caller method to be marked with async ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM