C# ConcurrentDictionary with Examples

In the previous blog&nbsp;<a href="http://code-adda.com/2018/12/c-dictionary-with-examples/" target="_blank">C# Dictionary with Examples</a>, we have learned about C# Dictionary and how to use it for different purposes like Initialization, adding values, reading values, etc. In this article, we are going to learn about&nbsp;<strong>ConcurrentDictionary&nbsp;</strong>and how to use it for different purposes.

In the previous blog C# Dictionary with Examples, we have learned about C# Dictionary and how to use it for different purposes like Initialization, adding values, reading values, etc. In this article, we are going to learn about ConcurrentDictionary and how to use it for different purposes.

ConcurrentDictionary

Represents a thread-safe collection of key/value pairs that can be accessed by multiple threads
concurrently.

The ConcurrentDictionary is a dictionary that allows you to add, fetch and remove items in a thread-safe way.

Note:

1. The ConcurrentDictionary type resides in System.Collections.Concurrent. It was introduced in .NET 4.0.

2. It makes adding, removing and updating values in a lookup table on multiple threads easier.

Before starting learning about ConcurrentDictionary, let us know why actually we need it and why we can not use C# Dictionary instead of C# ConcurrentDictionary. To make it clear please go through below code and try to write same in your VS and run it.

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

class ConcurrentDict
{
static void Main()
{
ConcurrentDictionary<int, string> con_dictionary = new ConcurrentDictionary<int, string>();
Dictionary<string, string> dictionary = new Dictionary<string, string>();

    Task t1 = Task.Factory.StartNew(() =&gt;
    {
        for (int i = 0; i &lt; 100; ++i)
        {
             con_dictionary.TryAdd(i, i.ToString());       

             // will generate error - System.ArgumentException: 'An item with the same key has already been added.'
            // dictionary.Add(i.ToString(), i.ToString()); 
        }
    });
    
    Task t2 = Task.Factory.StartNew(() =&gt;
    {
        for (int i = 0; i &lt; 100; ++i)
        {
             con_dictionary.TryAdd(i, i.ToString());                    
           // dictionary.Add(i.ToString(), i.ToString());
            Thread.Sleep(100);
        }
    });

    try
    {
        Task.WaitAll(t1,t2);
    }
    catch (AggregateException ex) // No exception
    {
        Console.WriteLine(ex.Flatten().Message);
    }
    Console.ReadLine();
}        

}

Just uncomment commented code – // dictionary.Add(i.ToString(), i.ToString()); and debug the code, There is error you’ll get stating “System.ArgumentException: ‘An item with the same key has already been added.'” which means in Dictionary once you allocate a key with the specific value you can never replace it. Fine! but what when you have to use Dictionary in the thread? In such a situation, you can use ConcurrentThread easily.

ConcurrentDictionary<TKey,TValue> provides some methods for performing different tasks like adding retrieving removing or updating key/value pairs in the dictionary

Add items in ConcurrentDictionary

TryAdd – We can use TryAdd method which basically attempts to add the specified key and value to the ConcurrentDictionary<TKey,TValue>

using System.Collections.Concurrent;

class ConcurrentDictionary
{
static void Main()
{
ConcurrentDictionary<int, string> dict = new ConcurrentDictionary<int, string>();
dict.TryAdd(1, "January"); //returns true
dict.TryAdd(2, "February"); //returns true
dict.TryAdd(3, "March"); //returns true

    dict.TryAdd(3, "April");    // returns false, means program will get execute but April will not replace March. 

    Console.ReadLine();
}        

}

Note:

TryAdd methods returns true if key/value pair is added, and

returns false if the key already exists in the dictionary

Updating Items in ConcurrentDictionary

TryUpdate – we can use TryUpdate method which basically checks whether the key has a specified value and if it does, updates the key with a new value. It is as same as  CompareExchange method, except that we use it for dictionary elements.


Note:

Compares two values for equality and, if they are equal, replaces the first value.

using System.Collections.Concurrent;

class ConcurrentDictionary
{
static void Main(string[] args)
{
ConcurrentDictionary<int, string> dict = new ConcurrentDictionary<int, string>();
dict.TryAdd(1, "January"); //returns true
dict.TryAdd(2, "February"); //returns true
dict.TryAdd(3, "March"); //returns true
dict.TryAdd(4, "Apr"); //returns true

    string updatedValue;
    bool returnTrue = dict.TryUpdate(4, "April", "Apr"); //Returns true
    dict.TryGetValue(4, out updatedValue);
    Console.WriteLine(updatedValue); //Display "April"

    bool returnsFalse = dict.TryUpdate(4, "Apr", "Apr"); //Returns false
    dict.TryGetValue(4, out updatedValue);  //Returns "April" Old value
    Console.WriteLine(updatedValue);    //Returns "April"
}

}

Removing Item from ConcurrentDictionary

TryRemove – We can use TryRemove method which basically removes and return the value that has the specified key from them. It returns True if the object removed successfully and false if not.

static void Main(string[] args)
{
ConcurrentDictionary<int, string> dict = new ConcurrentDictionary<int, string>();
dict.TryAdd(1, "January"); //returns true
dict.TryAdd(2, "February"); //returns true
dict.TryAdd(3, "March"); //returns true
dict.TryAdd(4, "April"); //returns true

  string removedItem;
  bool result = dict.TryRemove(4, out removedItem); //Returns true
  Console.WriteLine(removedItem); //Returns "April"

}


by RAVI RANJAN KUMAR


C/C++ vs. Rust: A developer’s perspective

C/C++ vs. Rust: A developer’s perspective

In this post, you'll see the difference between Rust and C/C++ in a developer’s perspective

Originally published by Maourice Gonzalez at https://www.onmsft.com

C++ is an incredibly fast and efficient programming language. Its versatility knows no bounds and its maturity ensures support and reliability are second to none. Code developed in C++ is also extremely portable, all major operating systems support it. Many developers begin their coding journey with the language, and this is no coincidence. Being object-oriented means it does a very good job of teaching concepts like classes, inheritance, abstraction, encapsulation and polymorphism. Its concepts and syntax can be found in modern languages like C#, Java and Rust. It provides a great foundation that serves as a high speed on ramp to the more popular, easier to use and modern alternatives.

Now it’s not all rosy. C++ has a very steep learning curve and requires developers to apply best practices to the letter or risk ending up with unsafe and/or poor performing code. The small footprint of the standard library, while most times considered a benefit, also adds to the level of difficulty. This means successfully using C++ to create useful complex libraries and applications can be challenging. There is also very little offered in terms of memory management, developers must do this themselves. Novice programmers could end up with debugging nightmares as their lack of experience leads to memory corruption and other sticky situations. This last point has lead many companies to explore fast performing, safe and equally powerful alternatives to C++. For today’s Microsoft that means Rust.

The majority of vulnerabilities fixed and with a CVE [Common Vulnerabilities and Exposures] assigned are caused by developers inadvertently inserting memory corruption bugs into their C and C++ code - Gavin Thomas, Microsoft Security Response Center

Rust began as a personal project by a Mozilla employee named Graydon Hoare sometime in 2006. This ambitious project was in pre-release development for almost a decade, finally launching version 1.0 in May 2015. In what seems to be the blink of an eye it has stolen the hearts of hordes of developers going as far as being voted the most loved language four years straight since 2016 in the Stack Overflow Developer Survey.

The hard work has definitely paid off. The end result is very efficient language which is characteristically object oriented. The fact that it was designed to be syntactically similar to C++ makes it very easy to approach. But unlike the aforementioned it was also designed to be memory safe while also employing a form of memory management without the explicit use of garbage collection.

The ugly truth is software development is very much a trial and error endeavor. With that said Rust has gone above and beyond to help us debug our code. The compiler produces extremely intuitive and user friendly error messages along with great direct linking to relevant documentation to aid with troubleshooting. This means if the problem is not evident, most times the answer is a click away. I’ve found myself rarely having to fire up my browser to look for solutions outside of what the Rust compiler offers in terms of explanation and documentation.

Rust does not have a garbage collector but most times still allocates and release memory for you. It’s also designed to be memory safe, unlike C++ which very easily lets you get into trouble with dangling pointers and data races. In contrast Rust employs concepts which help you prevent and avoid such issues.

There are many other factors which have steered me away from C++ and onto Rust. But to be honest it has nothing to do with all the great stuff we’ve just explored. I came to Rust on a journey that began with WebAssembly. What started with me looking for a more efficient alternative to JavaScript for the web turned into figuring out just how powerful Rust turns out to be. From its seamless interop…

Automatically generate binding code between Rust, WebAssembly, and JavaScript APIs. Take advantage of libraries like web-sys that provide pre-packaged bindings for the entire web platform. – Rust website

To how fast and predictable its performance is. Everything in our lives evolves. Our smartphones, our cars, our home appliances, our own bodies. C++ while still incredibly powerful, fast and versatile can only take us so far. There is no harm in exploring alternatives, especially one as exceptional and with as much promise as Rust.

What do you guys think? Have you or would you give Rust a try? Let us know your thoughts in the comments section below.

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading

Why you should move from Node.js to Rust in 2019

Rust Vs. Haskell: Which Language is Best for API Design?

7 reasons why you should learn Rust programming language in 2019

An introduction to Web Development with Rust for Node.js Developers

Why do C and C++ allow the expression (int) + 4*5?

Why is this&nbsp;<em>(adding a type with a value)</em>&nbsp;possible? (tried with g++ and gcc.)

(int) + 4*5;

Why is this (adding a type with a value) possible? (tried with g++ and gcc.)

I know that it doesn't make sense (and has no effect), but I want to know why this is possible.