Restartable Tasks with timed operation

隐身守侯 提交于 2021-01-29 14:25: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.

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.

I came up with the following idea:

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.

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.

I will refer to the above class as TimedTask.

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)

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.


回答1:


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


来源:https://stackoverflow.com/questions/61089181/restartable-tasks-with-timed-operation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!