Search code examples
c#multithreadingmmo

ConcurrentDict doesnt prevent items to be null inside an loop


foreach (KeyValuePair<uint, Character> kvp in World.AllChars)
{
    Character Charr = kvp.Value;
    Charr.Do(); <-- NullrefException: Charr is null
}

Code with the check:

foreach (KeyValuePair<uint, Character> kvp in World.AllChars)
{
    Character Charr = kvp.Value;
    if(Charr != null)
    {
       Charr.Do(); <-- NullrefException: Charr is null
    }
}

EDIT:

Nothing inside Do() causes it to be null, as it doesnt even get to execute Do() because Charr is null.

Thats how my loop looks like. I already tried to do a if != null check but it still goes past that and throws an nullref exception.

How can I prevent that? Im using a Concurrent Dictionary and a highly multithreaded server architecture.


Solution

  • If you have a null check for Charr added and still get a null reference exception something in the Do() Method will cause this exception. Check the call stack of the exception or/and use a debugger to go through your code step by step.