它的成本使用Task.Delay()?

编程入门 行业动态 更新时间:2024-10-25 10:32:50
本文介绍了它的成本使用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()?

本文发布于:2023-11-08 16:17:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1569862.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:成本   Task   Delay

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!