roflmuffin / CounterStrikeSharp

CounterStrikeSharp allows you to write server plugins in C# for Counter-Strike 2/Source2/CS2
https://docs.cssharp.dev
Other
756 stars 113 forks source link

feat: use concurrent queue for next frame & world update tasks #365

Closed roflmuffin closed 6 months ago

roflmuffin commented 6 months ago

Closes #354

roflmuffin commented 6 months ago

Tested this with pretty jank code, and confirmed the output is as expected, 1024 calls per frame until the queue is emptied.

// Queue next world updates from as many threads as possible
var times = new Dictionary<float, int>();
var tasks = new List<Task>();
for (int i = 0; i < 10000; i++)
{
    // Create a new task that will run on a random thread
    tasks.Add(Task.Run(async () =>
    {
        await Server.NextWorldUpdate(() =>
        {
            // Track the server (main thread) time when the task is executed
            times[Server.CurrentTime] = times.TryGetValue(Server.CurrentTime, out var time) ? time + 1 : 1;
        });
    }));
}

await Task.WhenAll(tasks);

Logger.LogInformation("{Times}", times);

{"14.25": 1024, "14.28125": 1024, "14.3125": 1024, "14.328125": 1024, "14.34375": 1024, "14.359375": 1024, "14.375": 1024, "14.40625": 1024, "14.421875": 1024, "14.4375": 784}