What is the best way to fake a lengthy parallel processing process?

I was wondering what is the best way to fake a long-term task when several tasks are performed in parallel. The first thing that comes to mind is Thread.Sleep

public void FakeLongRunningTask()
{
Thread.Sleep(5000);
}

However, the problem with the above code is that calling Thread.Sleep blocks this thread, which means that it will refuse CPU time, so calling a method with Thread.Sleep in a parallel environment is as good as not calling it at all, therefore, if I run three tasks in parallel, and one of them calls Thread.Sleep, this task will not affect performance (although this may cause the CLR to generate more threads !!!). But I want to fake a task that will affect overall performance.

+3
source share
3 answers

If you want to liven up a wait that will be supported by a single processor core, you can try something like this:

public void BusyWait(int milliseconds)
{
    var sw = Stopwatch.StartNew();

    while (sw.ElapsedMilliseconds < milliseconds)
        Thread.SpinWait(1000);
}
+5
source

Using box 4.5, I think you can use Task.Delay

EDIT: in response to the 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 framework 4.0 may work (unverified):

Task Delay(int interval)
{
     var z = new TaskCompletionSource<object>();
     new Timer(_ => z.SetResult(null)).Change(interval, -1);
     return z.Task;
}
+9
source

:

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

(, Big Daddy = D):

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

, await ( , async).

0

All Articles