My A Star move finder is freezing when I try to sort for the least-cost node. Can anyone tell why?

So I’m working on an A-Star program to find movement nodes in a basic four-way grid map, towards a target. I’m using dictionaries and serial numbers to sort things, and I have it mostly working. However, when I try to add the next neighbors to compare into a dictionary, it crashes. I’m not entirely sure why either:

	void DirectionFinder()
	{
		// Find Target Point //
		GetBoardPosition();
		BuildOrReBuildPawnRefBoard();
		bool IsTrue = false;
		int Serial = lastSquare.Location.Serial;
		// Get the Serial Keys of the nodes that are neighboring this node //
		bool TestNode = NodesClosed.ContainsKey(Serial);
		Dictionary<int, Node> SortArray = new Dictionary<int, Node>();
		SortArray.Clear();
		if (TestNode) 
		{
			Node ScanNode = NodesClosed[Serial];
			// Get the Number of Neighbors I have //
			int TestNumNeighbors = ScanNode.NeighborNodes.Count;
			// Set up a Loop that will go through these nodes and get the lowest-scored movement node //
			for (int loop = 0; loop < TestNumNeighbors; loop++)
			{
				int ScanNodePointX = ScanNode.NeighborNodes[loop].X;
				int ScanNodePointY = ScanNode.NeighborNodes[loop].Y;
				int ScanTestSerial = System_GameController.Instance.NodeArray[ScanNodePointX, ScanNodePointY].Location.Serial;
				bool IsNodeOpen = NodesOpen.ContainsKey(ScanTestSerial);
				if (IsNodeOpen)
				{
					Debug.Log("This Node is Open:" + ScanTestSerial);
					Node CompareNode = NodesOpen[ScanTestSerial];
					int CostOfNode = CompareNode.TotalCost;
					SortArray.Add(CostOfNode, CompareNode);
				}
			}
		}
	}

When it finishes finding it’s target, it moves, and looks again for the next target. I know that it could build up a vector direction array and follow that, but for the moment I’m not yet doing that.

I’m going to guess that CompareNode is null or you are putting duplicate Keys into the dictionary.

I made a video about how I did A* here.
There is a link in the description that goes to my code.
Using a MinHeap might solve your problem and it should be a faster sort.