We are working on a Azure Function App. We are using dependency injection. We are storing some data in a ‘public static IDictionary<string,List>’ in a class. We need to use same IDictionary later from another class. Concurrent invocation is modifying Dictionary, Which is causing silent loss of data. We need to share a a dictionary between three classes, which cannot be accessed from another concurrent invocation/thread. How can we implement it properly ?

We have implemented both class in following way

using System;
using System.Collections.Generic;

namespace ConsoleApp
{
    class Class1
    {
        public static IDictionary<string, List<String>> details;
        public Class1()
        {
            Class1.details = new Dictionary<string, List<string>>();
        }

        public void Method1()
        {
            Class1.details.Add("1", new List<string>() { "A1", "A2" });
        }
        public void Method2()
        {
            Class1.details.Add("2", new List<string>() { "B1", "B2" });
        }
    }

    class Class2
    {
        private readonly Class1 class1;
        public Class2(Class1 class1)
        {
            this.class1 = class1;
        }
        public void MethodXYZ()
        {
            Console.WriteLine(String.Join(";", Class1.details["1"]));
            Console.WriteLine(String.Join(";", Class1.details["2"]));
        }
    }

    class MyHttpTrigger
    {
        private readonly Class1 class1;
        private readonly Class2 class2;
        public MyHttpTrigger(Class1 class1, Class2 class2)
        {
            this.class1 = class1;
            this.class2 = class2;
        }

        [FunctionName("MyHttpTrigger")]
        public async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req)
        {
            this.class1.Method1();
            this.class1.Method2();
            //a lot of process
            this.class2.MethodXYZ();
        }
    }
}

When one invocation is running for a longer duration, Another concurrent invocation is creating a new Dictionary. So we losing data during execution. How can we implement this requirement properly?

1