I am new to C#'s ConcurrentDictionary
class, and I wonder how I can use a valueFactory in the GetOrAdd
method in an async way.
public class Class1
{
public int X = 10;
public Class1(int x)
{
X = x;
Debug.WriteLine("Class1 Created");
}
}
Testing code logic in a 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 GetOrAdd method is called in the second time, it returns a Task from the concurrent dictionary. Then I called await on the Task,
var temp2 = await (asyncDict.GetOrAdd(1,valueFactoryAsync)).ConfigureAwait(false);
it seems like the underlying Task(or async method) was not called again and return a new Class1 object.Was it just returned the Class1 object generated in the first call?
Could you advise what is happening under the hood?