它的成本使用Task.Delay()? [英] What it costs to use Task.Delay()?

查看:160
本文介绍了它的成本使用Task.Delay()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用C#异步\\伺机在MMO游戏服务器事件驱动逻辑。让我们假设有成千上万的实体做已知工期一些工作。所以,我想引用 Time.Delay()为每一位我的游戏对象。 (这是一个opposit方法常见的无限循环与一些更新()要求每场比赛的对象。)

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.)

有谁知道如何 Task.Delay()实施?
难道使用定时器?它是沉重的系统资源?

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

它是好的产卵数千并发 Task.Delay()调用?

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

推荐答案

Task.Delay 的实现方式是:

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

这绝对使用计时器。他们在一个叫做类中使用 DelayPromise 。下面是该实现:

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.

这篇关于它的成本使用Task.Delay()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆