I've read the MSDN documents and this blog and I need the following logic:
For a ConcurrentDictionary<string,bool>
- If the string doesn't exist, add it,and make sure I set the bool to
True
while adding - If the string does exist, only change the bool to
True
if it's false. Otherwise cancel the update
My use case
I have several DNS Domains to scan for malware. There is a good likelihood that there will be duplicates in the list that I retrieve in realtime. I receive the list of DNS Domains in batches of 100 or less, and there will be over 10,000 domains to scan.
I only want to scan a DNS host once per iteration of 10,000 domains. A bool == true
means it's currently being scanned and I should cancel the task before I go any further. A bool == false
or no entry means I should immediately update the entry as bool==true
or create a new entry ASAP.
Keep in mind...
AddOrUpdate will be called independently from many independent threads in .NET4's TPL. Each thread needs to decide if it needs to work on the value mentioned in Dictionary's key
... or proceed to the next one. Only one "key" should ever have work done to it.
I need to signal to the calling thread that the update succeeded or failed. In addition according to this answer it seems that AddOrUpdate's functions will be called many times. I think this may mean my calling threads will be confused as to cancel work on key
or to continue it. (remember only one thread can be actively working on key
Example of concurrent updates that may confuse the calling thread
ConcurrentDictionary<int, string> numbers = new ConcurrentDictionary<int, string>();
Parallel.For(0, 10, x =>
{
numbers.AddOrUpdate(1,
i =>
{
Console.WriteLine("addValueFactory has been called");
return i.ToString();
},
(i, s) =>
{
Console.WriteLine("updateValueFactory has been called");
return i.ToString();
});
});
Output
addValueFactory has been called
addValueFactory has been called
addValueFactory has been called
addValueFactory has been called
updateValueFactory has been called
updateValueFactory has been called
updateValueFactory has been called
updateValueFactory has been called
updateValueFactory has been called
updateValueFactory has been called
updateValueFactory has been called
updateValueFactory has been called
updateValueFactory has been called
Question
How should I add this "cancel update" functionality to AddOrUpdate?