Can ConcurrentDictionary.GetOrAdd() be called recursively?
<p><a href="http://ConcurrentDictionary%3CTKey,%E2%80%82TValue%3E.GetOrAdd%20Method%20(TKey,%E2%80%82Func%3CTKey,%E2%80%82TValue%3E)" rel="noreferrer">ConcurrentDictionary.GetOrAdd(TKey, Func&lt;TKey, TValue&gt;)</a> accepts a factory function to allow lazy instantiation of the item to be put into the dictionary.</p>

<p>Is it safe to define a factory function that itself calls GetOrAdd(), i.e. GetOrAdd is being called within the context of a 'parent' GetOrAdd().</p>

<p>The following code demonstrates the pattern; It does appear to work, but is it safe?</p>

<pre><code>class Program
{
    static ConcurrentDictionary&lt;string,object&gt; __dict = new ConcurrentDictionary&lt;string, object&gt;();

    static void Main(string[] args)
    {
        Foo foo = GetOrAddFoo();
        Console.WriteLine(foo._name);
        Console.WriteLine(foo._bar._name);
        Console.ReadKey();
    }

    static Bar GetOrAddBar()
    {
        Console.WriteLine("GetOrAddBar: enter");
        Func&lt;string,Bar&gt; factoryFn = (x) =&gt; LoadBar(x);
        Bar bar = __dict.GetOrAdd("bar", factoryFn) as Bar;
        Console.WriteLine("GetOrAddBar: exit");
        return bar;
    }

    static Foo GetOrAddFoo()
    {
        Console.WriteLine("GetOrAddFoo: enter");
        Func&lt;string,Foo&gt; factoryFn = (x) =&gt; LoadFoo(x);
        Foo foo = __dict.GetOrAdd("foo", factoryFn) as Foo;
        Console.WriteLine("GetOrAddFoo: exit");
        return foo;
    }

    static Bar LoadBar(string name)
    {
        Bar bar =  new Bar();
        bar._name = name;
        return bar;
    }

    static Foo LoadFoo(string name)
    {
        Foo foo = new Foo();
        foo._name = name;
        foo._bar = GetOrAddBar();
        return foo;
    }

    public class Foo
    {
       public string _name;
       public Bar _bar;
    }

    public class Bar
    {
        public string _name;
    }
}
</code></pre>