Call valuefactory in a parallel dictionary in asynchronous mode

I am new to C # class ConcurrentDictionary, and I am wondering how I can use valueFactory in a method in GetOrAddan asynchronous way.

public class Class1
{
    public int X = 10;

    public Class1(int x)
    {
        X = x;
        Debug.WriteLine("Class1 Created");
    }
}

Testing the logic of the code in the WinForm button:

private async void button1_Click(object sender, EventArgs e)
{
    var asyncDict = new ConcurrentDictionary<int, Task<Class1>>();

    Func<int, Task<Class1>> valueFactoryAsync = async (k) => new Class1(await Task.Run(async () =>
    {
        await Task.Delay(2000);
        Debug.WriteLine("Async Factory Called");
        return 5;
    }));

    var temp = await(asyncDict.GetOrAdd(1, valueFactoryAsync)).ConfigureAwait(false);
    Debug.WriteLine(temp.X);
    temp.X = 20;
    var temp2 = await (asyncDict.GetOrAdd(1, valueFactoryAsync)).ConfigureAwait(false);
    Debug.WriteLine(temp2.X);
}

When the GetOrAdd method is called a second time, it returns the task from the parallel dictionary. Then I called var temp2 = await (asyncDict.GetOrAdd(1,valueFactoryAsync)).ConfigureAwait(false); Task , it looks like the main task (or async method) was not called again and returns a new Class1 object. Should he just return the Class1 object generated on the first call? Could you advise what is happening under the hood?

+4
source share
2 answers

, , asyncDict.GetOrAdd(1,valueFactoryAsync) . ? , .

?

var temp = await(asyncDict.GetOrAdd(1, valueFactoryAsync)).ConfigureAwait(false);

, = 1, valueFactoryAsync, = , . Add. Get, . (var temp = await (...)), , , . , - , await (asyncDict.GetOrAdd(1, valueFactoryAsync)) - temp2 - - . , , Created Task, (, , Class1, await/.Result it)

0

shay__ . , GetOrAdd factory . , . , ConcurrentDictionary<TKey, Lazy<TValue>>. TValue = Task<Class1>. , .

ConcurrentDictionary .

0

All Articles