Let's say I have the following code:
class Test
{
Dictionary<int, Task> tasks;
void Run()
{
tasks.Add(1, DoStuff(1));
tasks.Add(2, DoStuff(2));
tasks.Add(3, DoStuff(3));
}
async Task DoStuff(int id)
{
try
{
// Do stuff that takes a lot of time and can end unsuccessfully.
}
finally
{
tasks.Remove(id);
}
}
}
If I know for sure that task can remove only itself and all ids will be different (newly generated guid for instance) - can I leave this code as is? Or do I need some kind of locking or using ConcurrentDictionary here because internals of regular Dictionary or List can fail when accessed concurrently? (let's say there is 10000 tasks like this and they all end at the same time)
Also: nobody will ever read this dictionary/list or iterate through it. It is used solely for the purpose of keeping references to the background tasks (so GC doesn't collect them). If you have a better proposal for that use case please suggestions are welcome :)
Dictionary<TKey,TValue>does not contain an element with the specified key, theDictionary<TKey,TValue>remains unchanged. No exception is thrown." It doesn't mean that it's thread-safe, however .