Introduction:
In a previous post I'd talked about the Dictionary type. Ever wonder if there's a thread-safe version out there to use? ConcurrentDictionary is what you seek. Introduced in .net 4.0, we still get the same key/value pairing available before. But enough about definitions, lets do some coding.
Coding:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.Concurrent;
namespace DictionarySample
{
class Program
{
static void Main(string[] args)
{
//step 1: create!
ConcurrentDictionary<string, string> theRain = new ConcurrentDictionary<string, string>();
theRain.GetOrAdd("Daniel", "c0d3r");
theRain.GetOrAdd("Bob", "$ql script kiddi3");
theRain.GetOrAdd("Dan", "c0d3r");
theRain.GetOrAdd("Peter", "t@$k m@$t3r");
//step 2: test
Console.WriteLine("Testing time of our ConcurrentDictionary");
Console.WriteLine("does myDic.ContainsKey(chode)? : " + theRain.ContainsKey("chode").ToString() + " ");
Console.WriteLine("does myDic.ContainsKey(Peter)? : " + theRain.ContainsKey("Peter").ToString() + " ");
Console.WriteLine("does myDic.ContainsKey(peter)? : " + theRain.ContainsKey("peter").ToString() + " ");
Console.WriteLine();
// step 3: write out data
Console.WriteLine("initial data value(s) loaded in our ConcurrentDictionary");
foreach (var pair in theRain)
Console.WriteLine(pair.Key + " " + pair.Value);
// step 4: update some data.
theRain.TryUpdate("Peter", "koala", "Uber");
Console.WriteLine();
Console.WriteLine("value of Peter : " + theRain["Peter"]);
Console.WriteLine();
theRain.TryUpdate("Peter", "koala", "t@$k m@$t3r");
Console.WriteLine();
Console.WriteLine("value of Peter : " + theRain["Peter"]);
Console.WriteLine();
//step 5: write out the data
Console.WriteLine("Modified data value(s) loaded in our ConcurrentDictionary");
foreach (var pair in theRain)
Console.WriteLine(pair.Key + " " + pair.Value);
Console.WriteLine("\nPress Any Key to Exit.");
Console.ReadKey();
}
}
}
Step 1: The constructor part is easy enough, create it quite similarly like we did with the Dictionary blog.
Step 2: doing some QA to see if ConcurrentDictionary really does act like the regular Dictionary. It does!
Step 3: displaying the data to verify what was originally created exists as we expect.
Step 4: Attempting to update some data, for my sample I'm going to turn the key Peter into the value of koala instead of t@$k m@$t3r. As the value of Peter isn't Uber it won't update. As the value of Peter is t@$k m@$t3r it will update and now Peter is a koala.
Step 5: displaying out the data to verify what we've modified exists as we expect.
and the output:
Source:

No comments:
Post a Comment