5.5 C
New York
Saturday, March 15, 2025

monogame – Understanding C# Duties


I take advantage of quite a lot of path discovering in my Monogame venture which is taking a toll on the framerate, as a result of within the worst case discovering a path can take 200ms. So I regarded into utilizing Duties to unfold path discovering computation over a number of frames and possibly even compute them concurrently.

This required me to rewrite the trail discovering system right into a model that I believe is slower, and which undoubtedly ought to use extra reminiscence. Nevertheless! Once I received it to work, the trail discovering now takes at most 8ms, and the reminiscence utilization in line with Visible Studio has fallen by ~100MB.

That is good in fact, however simply within the curiosity of understanding what is going on on, can somebody clarify why that is?

The modifications I constructed from earlier than to after was mainly to take away static path discovering knowledge, so that every process can have its personal copy, after which I stuffed the trail discovering calls right into a lambda and fed it to the Duties.

Earlier than:

whereas (requestQueue.Rely > 0)
{
    PathRequest request = requestQueue.Dequeue();

    Record path = AStar.FindPathList(map, request.origin, request.goal);
    if (path == null)
    {
        Debug.Warn("Unable to seek out path.");
    }
    else
    {
        path = AStar.SimplifyPath(path);
    }
}

After:

whereas (requestQueue.Rely > 0)
{
    PathRequest request = requestQueue.Dequeue();

    Process pathTask = Process.Run(() =>
    {
        Record path = AStar.FindPathList(map, request.origin, request.goal);
        if (path == null)
        {
            Debug.Warn("Unable to seek out path.");
        }
        else
        {
            path = AStar.SimplifyPath(path);
        }

        request.returnAction(path);
    });
}

How I make requests:

Tile origin = map.tiles.Get(/* ... */));
Tile goal = map.tiles.Get(/* ... */));

pathManager.MakePathRequest(ReturnAction, origin, goal);
agent.isAwaitingPath = true;

void ReturnAction ( Record path )
{
    agent.isAwaitingPath = false;

    if (path == null)
        agent.remodel.WorldPosition = new Vector2(map.BorderSize * 4, map.BorderSize * 4);
    else
        agent.path = path;
}

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles