2

I have a class that maintains a static Dictionary to contain a map between string and another Object (CloudFileClient in my case). I haven't used static constructor but rather have initialized the variable while declaring.

Problem:

I am facing "Object reference not set to an instance of an object." exception while adding a key to the dictionary. From the stack trace it looks like the Dictionary itself maybe null.

Sample code:

public class Demo
{
    // Initalizing the dictionary here.
    private static Dictionary<string, CloudFileClient> CloudFileClientReferences = new Dictionary<string, CloudFileClient>();
    ...

    public static Func<string, CloudFileClient> GetCloudFileClient { get; set; } = (string accountName) =>
    {
        if (!CloudFileClientReferences.ContainsKey(accountName))
        {
            CloudFileClientReferences[accountName] = CreateCloudFileClient(); // Problem statement.
        }
        ...
    }
}

This seems to work fine but occassionaly the app is logging the following error at the "Problem statement" line.

Object reference not set to an instance of an object. at System.Collections.Generic.Dictionary2.TryInsert(TKey key, TValue value, InsertionBehavior behavior) \r\n at System.Collections.Generic.Dictionary2.set_Item(TKey key, TValue value)

What could be the issue here? I have hosted this code within Azure serverless function. I don't think ConcurrentDictionary would help here as the error would say so. Can a null key cause this? Or should I use static constructor instead?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Gautam Kumar Samal
  • 758
  • 1
  • 7
  • 23
  • 1
    _"...I don't think ConcurrentDictionary would help here..."_ Would have been easy to try out, wouldn't it? – Uwe Keim Feb 21 '22 at 10:54
  • 1
    Sounds like a multithreading problem that has provoked an error within the `Dictionary` implementation. – Matthew Watson Feb 21 '22 at 10:54
  • Does this answer your question? [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – derpirscher Feb 21 '22 at 10:55
  • 1
    Fundamentally, even if you *didn't* have this problem, you're using the not-thread-safe `Dictionary<,>` class in a mutable way potentially across multiple thread. Why would you expect the error to tell you that `ConcurrentDictionary` would solve the issue? – Jon Skeet Feb 21 '22 at 10:58
  • @UweKeim yes, I am going forward with that change. It will take some time to deploy and check. As I said it's happening randomly and I am not able to reproduce it in local system. Would be good to know, why the reference seems to be null even there is a clear initialization. – Gautam Kumar Samal Feb 21 '22 at 10:58
  • @JonSkeet it doesn't as I said. I would except errors like "Operations that change non-concurrent collections must have exclusive access. A concurrent update was performed on this collection and corrupted its state." to know that multi-threaded access is the cause here. – Gautam Kumar Samal Feb 21 '22 at 11:00
  • Could this help https://stackoverflow.com/questions/1320621/throw-a-nullreferenceexception-while-calling-the-set-item-method-of-a-dictionary – Christopher Hamkins Feb 21 '22 at 11:01
  • 2
    @GautamKumarSamal: I was asking *why you would expect* it to say that. Do you have any evidence that it does that anywhere else? Typically non-thread-safe types like `Dictionary<,>` don't try to detect that you're using you're misusing them. – Jon Skeet Feb 21 '22 at 11:02
  • @GautamKumarSamal It's easy to show that it DOESN'T give you such warnings. Try this: https://dotnetfiddle.net/nADYct (you may need to run it several times to see an error). – Matthew Watson Feb 21 '22 at 11:03
  • @JonSkeet I understand. I have faced error related to multi-threaded operations on a dictionary. Those always have a hint "concurrent" in the exception. Here it says that something is not an instance of object, essentially null I assume. Do you mean a multi-threaded access can trigger the said exception? – Gautam Kumar Samal Feb 21 '22 at 11:08
  • @derpirscher you are right. It's actually like "System.Collections.Generic.Dictionary`2". I copied it from an editor that trated it as a markdown syntax. Sorry for that. – Gautam Kumar Samal Feb 21 '22 at 11:12
  • 1
    @GautamKumarSamal: I can't say I've ever personally seen an error message like that for `Dictionary<,>`. But fundamentally you're using a type "off-label" - https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2?view=net-6.0#thread-safety specifically says that what you're doing is not safe. – Jon Skeet Feb 21 '22 at 11:15
  • @JonSkeet I guess so. I'll try the concurrent dictionary and will update if it resolved things for me. – Gautam Kumar Samal Feb 21 '22 at 11:20

0 Answers0