21

I am thinking on using C# async\await in MMO game server with event-driven logic. Let's assume there are thousands of entities doing some work with known durations. So I would like to invoke Time.Delay() for every of my game objects. (This is an opposit approach to common infinite loop with some Update() call for every game object.)

Does anybody knows how is Task.Delay() implemented? Is it using timers? Is it heavy on system resources?

Is it okay to spawn thousands of simultaneous Task.Delay() invocations?

6
  • 4
    @ColeJohnson Because Thread.Sleep isn't async? Jun 29, 2013 at 9:13
  • And Task.Delay is? That doesn't make sense. If I want to delay a thread, I want it NOW, not spawning another thread to tell one to halt.
    – Cole Tobin
    Jun 29, 2013 at 9:15
  • @Cole The point is to make a thread wait some time before resuming. The point isn't to delay a thread. Jun 29, 2013 at 9:18
  • 3
    @ColeJohnson The await/async stuff causes a call to Task.Delay() to appear to return immediately from the code that calls it, and the code following the delay will resume after the delay is over. It's non-blocking (as long as the method calling it is itself async). Jun 29, 2013 at 9:26
  • 1
    @It'sNotALie. because calling Thread.Sleep with argument other than 0 or 1 is always a big design problem. Oct 4, 2016 at 9:58

2 Answers 2

24

Task.Delay is implemented as follows:

public static Task Delay(int millisecondsDelay, CancellationToken cancellationToken)
{
  //error checking
  Task.DelayPromise delayPromise = new Task.DelayPromise(cancellationToken);
  if (cancellationToken.CanBeCanceled)
    delayPromise.Registration = cancellationToken.InternalRegisterWithoutEC((Action<object>) (state => ((Task.DelayPromise) state).Complete()), (object) delayPromise);
  if (millisecondsDelay != -1)
  {
    delayPromise.Timer = new Timer((TimerCallback) (state => ((Task.DelayPromise) state).Complete()), (object) delayPromise, millisecondsDelay, -1);
    delayPromise.Timer.KeepRootedWhileScheduled();
  }
  return (Task) delayPromise;
}

It definitely uses timers. They're used in a class called DelayPromise. Here's the implementation for that:

private sealed class DelayPromise : Task<VoidTaskResult>
{
  internal readonly CancellationToken Token;
  internal CancellationTokenRegistration Registration;
  internal Timer Timer;

  internal DelayPromise(CancellationToken token)
  {
    this.Token = token;
  }

  internal void Complete()
  {
    if (!(this.Token.IsCancellationRequested ? this.TrySetCanceled(this.Token) : this.TrySetResult(new VoidTaskResult())))
      return;
    if (this.Timer != null)
      this.Timer.Dispose();
    this.Registration.Dispose();
  }
}

It does use a timer, but it doesn't seem like a worry to me. The timer just calls back to the complete method, and what that does is check if it's canceled, if so cancel it, else just return a result. It seems fine to me.

8
  • 1
    I'm actually surprised that it creates a new timer object for each Delay. I would have thought it would use some delta-queue with one timer. Jun 29, 2013 at 10:23
  • 1
    As said in MSDN documentation: "System.Threading.Timer is a simple, lightweight timer that uses callback methods and is served by threadpool threads." To me "lightweightness" and "threadpool threads" seem to be incompatible concepts. Jun 29, 2013 at 10:34
  • 6
    I believe that the actual (unmanaged) implementation does use a delta-queue. Still, if you have many, many Delay calls, you'll be creating a lot of garbage and it wouldn't be the most efficient solution. If your "thousands of entities" are doing several things a second, I'd consider alternatives. Jun 29, 2013 at 13:01
  • 1
    I meant the System.Timers.Timer implementation, part of the CLR. And I'm going from memory after looking it up years ago - I may be wrong. Jun 29, 2013 at 13:18
  • 9
    The .NET Timer implementation wraps the Win32 timer queue, which is a delta-queue that fires events on the thread pool. More info here: msdn.microsoft.com/en-us/library/ms686796%28v=VS.85%29.aspx
    – Chuu
    Oct 5, 2015 at 14:14
0

In .NET Core Task.Delay is implemented via TimerQueue. It does not create a new Timer every time. From what I can see from source code it instead it creates N "queues", where N is the number of CPU cores. And then it uses 1 (one) timer for each queue.

This is more lightweight than the .NET Framework approach, but still there's a sh*tload of code executed every time you call a Task.Delay. I wish there was a better way.

P.S. Just adding a more up to date version for google-searchers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.