await Delay or use timers

时间:2017-06-15 09:43:29

标签: c# .net-core

I have a hard time getting my head around this.

I need to execute few methods, each one delayed by an amount of time. So from what I could read, I can use Task.Delay or a Timer as it seems internally, Task.Delay is using a Timer.

So are the two following approach equivalent? If not, what would be the pros and cons of each approach?

What happens to the calling thread for each approach? I really don't want to block the thread. I don't think either of those 2 approaches do though.

1st approach:

public async Task SimulateScenarioAsync()
{
    await Task.Delay(1000).ConfigureAwait(false);
    await FooAsync.ConfigureAwait(false);

    await Task.Delay(2000).ConfigureAwait(false);
    await BarAsync.ConfigureAwait(false);

    await Task.Delay(500).ConfigureAwait(false);
    await StuffAsync.ConfigureAwait(false);
}

2nd approach:

public void SimulateScenario()
{
    var timer = new Timer(new TimerCallback(FooAsync), null, 1000, Timeout.Infinite);
}

public void FooAsync(Object obj)
{
    // do some stuff
    var timer = new Timer(new TimerCallback(BarAsync), null, 2000, Timeout.Infinite);
}

public void BarAsync(Object obj)
{
    // do some stuff
    var timer = new Timer(new TimerCallback(StuffAsync), null, 500, Timeout.Infinite);
}

public void StuffAsync(Object obj)
{
    // do some stuff
}

2 个答案:

答案 0 :(得分:1)

I think that first approach is more readable.

Other than that, I can't see any reason for picking either method. If you wait for 1 second between operations, it doesn't really matter what is the performance of that command for sure it will be at least 1000x faster than your waiting period.

答案 1 :(得分:0)

This question suggests wrapping it in a single call like this

async Task MyTaskWithDelay()
{
    await Task.Delay(1000);
    MyTask();
}

Comparing the two approaches

This answer says

There are two major differences:

  1. The Task.Delay approach will delay the specified amount of time between cycles, while the DispatcherTimer approach will start a new cycle on the specified cycle time.
  2. Task.Delay is more portable, since it does not depend on a type tied to a specific UI.

And this post says

The Task.Delay will block the thread for the specified time. While DispatcherTimer creates a separate thread for the timer and then return to the original thread after the specified time.