具有定时操作的可重启任务 [英] Restartable Tasks with timed operation

查看:53
本文介绍了具有定时操作的可重启任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在清理网络同步对象时遇到问题:在每个刻度上,服务器向客户端(不可靠地)发送该玩家周围对象的状态(位置、四元数).

I have an issue with cleaning up network-synced objects: On each tick the server sends the client (Unreliably) the states (Position, Quaternion) of objects around that player.

为了提高客户端的性能,我希望清理(隐藏或处理)X 时间未更新的对象.

In order to increase performance on the Client side, I wish to clean (hide or dispose) of objects that are not updated for X time.

我想出了以下想法:

实现类似于 JavaScript 的 setTimeout 的机制.该机制应支持运行中终止以及使用相同的参数集重新启动.

Implement a mechanism similar to JavaScript's setTimeout. The mechanism should support mid-run termination as well as restarting with the same set of args.

我想创建一个 class 来实现 Task 并接受 ushort 作为超时间隔,以及在时间结束后执行的 Action/Function通过.

I thought of creating a class which implements Task and accepts ushort as timeout interval, and Action/Function to perform after the time had passed.

我将上面的类称为TimedTask.

TimedTask 将有 2 个内部线程/任务:1.线程/任务1将负责睡眠直到超时2. thread/task2 将负责接收运行中的命令(例如,重启、停止、终止)

TimedTask would have 2 inner threads/tasks: 1. thread/task1 would be in charge of the sleep until the timeout 2. thread/task2 would be in charge of receiving mid-run commands (for instance, restart, stop, terminate)

TimedTask 可以存活很长时间,具体情况视情况而定,可能有超过 20-100 个 TimedTask 并行运行.

The TimedTask can live a long time and it depends on the circumstances, and there might be more than 20- 100 TimedTasks running in parallel.

我担心上面的实现会导致严重的性能问题,可能有更好的方法来解决这个问题,我是否应该循环遍历我的客户端在每个滴答声中的每个网络对象并查看哪些没有更新?

I'm afraid the above implementation will cause major performance issues, and there might be a better way to solve this problem, should I loop over each networked object my client has on every tick and see which ones were not updated?

如果你们有任何建议,我将不胜感激.

If you guys have any suggestion I'd appreciate it.

推荐答案

查看 PauseTokenSource 类由 Stephen Toub 提供(也可在 AsyncEx.Coordination 包由 StephenCleary 编写).您可以拥有数百个长期任务,每个任务都由单独的 PauseTokenSource 控制.性能取决于您在每项任务中所做的工作.暂停机制的开销应该可以忽略不计,除非您预计每秒循环约 100,000 次或更多(对于所有任务总计).

Take a look at the PauseTokenSource class by Stephen Toub (also available in the AsyncEx.Coordination package by StephenCleary). You could have hundreds of long lived tasks, each one controlled by a separate PauseTokenSource. The performance would depend on what you are doing inside each task. The overhead of the pausing mechanism should be negligible, unless you are anticipating a frequency of ~100,000 loops per second or more (for all tasks in total).

using Nito.AsyncEx;

async Task CreateLongLivedTask(PauseToken pauseToken, CancellationToken cancellationToken)
{
    while (true)
    {
        await pauseToken.WaitWhilePausedAsync(cancellationToken);
        DoImportantStuff();
        await Task.Delay(100, cancellationToken); // 10 loops per second
    }
}

这篇关于具有定时操作的可重启任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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