Memory Leak caused by Multi Threading

I am creating a board game similar to tic tac toe, and I’ve created an AI to play that game. The AI is very CPU intensive, so I decided to put it on it’s own thread. I’m using this plugin to do multithreading: Unity Asset Store - The Best Assets for Game Making .

I have this IEnumerator:

static IEnumerator executeAITurn(Turn turn) {
    Vector2[] move = mctsManager.mcts(new State(sections, null, turn), AIIterations)[0, 0].metaData.lastMove;

    yield return Ninja.JumpToUnity;

    input(move, true);

    yield return Ninja.JumpBack;

    Debug.Log("DONE!");
}

and I run it using

gameManager.StartCoroutineAsync(executeAITurn((AITurn == Turn.X) ? Turn.O : Turn.X));

Normally when I run executeAITurn it works normally without problems, but for some reason sometimes when I run it, it does what it’s supposed to but in task manager my memory just increases by 200 mb, and stays there. After that as I continue running executeAITurn the memory just keeps on increasing to like over 1000 mb, and then gets extremely slow.

Another thing is that if I click the play button again to stop the game, the memory still stays that high.

Any help would be appreciated.

EDIT:

mctsManager Class: MCTS - Pastebin.com

input Function: Input Function - Pastebin.com

You are constantly creating new states: new State(sections, null, turn)
which creates a new object everytime and cause memory to heap up.

Instead you could create one state, and edit the state the next time.
Like so:

 static State stateData = new State();
 static IEnumerator executeAITurn(Turn turn) {

//change existing state
stateData.Sections = sections;
stateData.SecondVar = null;
stateData.Turn = turn;

     Vector2[] move = mctsManager.mcts(stateData, AIIterations)[0, 0].metaData.lastMove;
     yield return Ninja.JumpToUnity;
     input(move, true);
     yield return Ninja.JumpBack;
     Debug.Log("DONE!");
 }

That might have some performance improvement.
Other than that you’re not providing enough information for us to see what is causing this.
For example what is your input method what does mctsManager.mcts do?
etc…