Using the BlockingCollection for thread-safe producer-consumer scenarios in .NET Part 1

We’ve looked at the 4 concurrent, i.e. thread-safe collections available in .NET:

We also mentioned that 3 of these, i.e. the concurrent queue, bag and stack implement the generic IProducerConsumer interface. They can be used in producer-consumer scenarios where one or more threads write to a work queue. They are the producers in the setup. One or more other threads then read from the same work queue in order to perform some task on them. These are the consumers. When the consumer takes an item from the work queue then that item is also removed from it so that it’s not processed more than once. If you need to build a scenario like that then you’ll obviously need thread-safe collections that can synchronise access to them in a reliable manner.

We haven’t seen before how a producer-consumer scenario can be built from scratch using the available classes in the System.Collections.Concurrent namespace. We’ll do that in this and the next couple of posts.

Read more of this post

How to hide the text entered in a .NET console application

You’ve probably encountered console applications that ask for a password. It’s very likely that the password will stay hidden otherwise other people viewing your screen can easily read it.

This short post will present a possible solution on how to achieve a hidden string input in a .NET console application.

Read more of this post

Calculate standard deviation of integers with C# .NET

Here comes a simple extension method to calculate the standard deviation of a list of integers:

public static double GetStandardDeviation(this IEnumerable<int> values)
{
	double standardDeviation = 0;
	int[] enumerable = values as int[] ?? values.ToArray();
	int count = enumerable.Count();
	if (count > 1)
	{
		double avg = enumerable.Average();
		double sum = enumerable.Sum(d => (d - avg) * (d - avg));
		standardDeviation = Math.Sqrt(sum / count);
	}
	return standardDeviation;
}

Here’s how you can call this method:

List<int> ints = new List<int>() { 4, 7, 3, 9, 13, 90, 5, 25, 13, 65, 34, 76, 54, 12, 51, 23, 3, 1, 7 };
double stdev = ints.GetStandardDeviation();

View all various C# language feature related posts here.

A common platform for concurrent bags, stacks and queues in .NET

We’ve looked at the available concurrent collections in .NET before:

3 of these objects implement the same interface. Can you guess which three are similar in some sense? Stacks, bags and queues differ from dictionaries in that elements in those collections cannot be retrieved by an index of any sort. You can take/pop/dequeue the elements one by one but you cannot get to element #3 without first removing all elements before that.

Read more of this post

Explicit interface implementation in .NET Part 4

In the previous post we finally solved the mystery of how the Add method was “hidden” in the ConcurrentDictionary object. We now know how explicit interface implementation works in code.

However why would you implement an interface explicitly?

Read more of this post

Explicit interface implementation in .NET Part 3

In the previous post we started looking into how explicit interface implementation is done in code. Visual Studio makes it a breeze and you can easily produce code like we saw previously:

int IMultipliable.Calculate(int a, int b)
{
	...
}

So now we can reach the Calculate methods as follows:

Read more of this post

Explicit interface implementation in .NET Part 2

In the previous post we introduced the idea of explicit interface implementation in .NET. We also saw two examples from .NET with explicit implementation in action.

Let’s first see how this language structure works in C#. Suppose we have the following interface:

public interface ISummable
{
	int Calculate(int a, int b);
}

We can then implement this interface implicitly as follows:

public class Calculator : ISummable
{
	public int Calculate(int a, int b)
	{
		return a + b;
	}
}

This should be straightforward for all programmers.

Let’s have another interface:

public interface IMultipliable
{
	int Calculate(int a, int b);
}

We then want our calculator to implement the above interface as well:

public class Calculator : ISummable, IMultipliable
{
	public int Calculate(int a, int b)
	{
		return a + b;
	}
}

As Calculator already has a Calculate method with two integer parameters it also satisfies IMultipliable without changing the Calculator object implementation.

This is problematic as we have no straightforward way to provide a multiplication for our calculator:

Calculator calculator = new Calculator();
int res = calculator.Calculate(2, 5);

“res” will be 7 of course.

We assume here that we cannot change the method names of ISummable and IMultipliable. They may be part of a third party library. One way out of this situation is to implement IMultipliable explicitly. If you right-click “IMultipliable” in Calculator.cs in Visual Studio you can select “Implement Interface”, “Implement Interface Explicitly” in the context menu. You’ll get the following stub:

public class Calculator : ISummable, IMultipliable
{
	public int Calculate(int a, int b)
	{
		return a + b;
	}

	int IMultipliable.Calculate(int a, int b)
	{
		throw new NotImplementedException();
	}
}

The structure of the new Calculate method looks very much like the non-generic GetEnumerator method of the second example of the previous post.

Explicitly implemented interface methods must not have any access modifiers. They are public by default.

Let’s implement the new method:

int IMultipliable.Calculate(int a, int b)
{
	return a * b;
}

How can we call this method? We have to declare Calculator as an interface type:

public void ShowSample()
{
	IMultipliable calculator = new Calculator();
	int res = calculator.Calculate(2, 5);
}

“res” will now be 10.

We’ll investigate this further in the next post.

View all various C# language feature related posts here.

Explicit interface implementation in .NET Part 1

The generic and well-known Dictionary object and its generic and thread-safe counterpart, i.e. the ConcurrentDictionary object both implement the generic IDictionary interface. The IDictionary interface has an Add method where you can insert a new key-value pair into a dictionary:

Dictionary<string, string> singleThreadedDictionary = new Dictionary<string, string>();
singleThreadedDictionary.Add("Key", "Value");

I can even rewrite the above code as follows:

IDictionary<string, string> singleThreadedDictionary = new Dictionary<string, string>();
singleThreadedDictionary.Add("Key", "Value");

However, what if we try to do the same with the concurrent dictionary?

Read more of this post

Using a thread-safe dictionary in .NET C# Part 4: thread-safe insertlookups

In the previous post we looked at how the AddOrUpdate method worked. We saw that it was a very neat and thread-safe way to either insert a new key-value pair or update an existing one.

We’ve already seen a thread-safe method that helps you retrieve values by their keys in this post: TryGet. It returns true if the item could be retrieved. TryAdd on the other hand is used to insert a new key-value pair. It also returns true if the item could be inserted successfully. However, what do you do with the returned boolean values? Do you keep trying in some loop until it succeeds?

Read more of this post

Using a thread-safe dictionary in .NET C# Part 2: CRUD operations

In the previous post we briefly introduced the ConcurrentDictionary object. We said that it was the thread-safe counterpart of the standard Dictionary object. The Dictionary object is not suited as a shared resource in multi-threaded scenarios as you can never be sure if another thread has added to or removed an element from the dictionary just milliseconds earlier. A ConcurrentDictionary is a good option to cure the shortcomings of the thread-sensitive Dictionary object but it is also more difficult to use.

We’ll briefly look at the 4 Try methods that enable you to insert, remove, update and lookup elements in the ConcurrentDictionary.

Read more of this post

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

ARCHIVED: Bite-size insight on Cyber Security for the not too technical.