. NET 4.0 new namespace: System. Collections. Concurrent

Source: Internet
Author: User
Document directory
  • Why Concurrent?
  • What Concurrent sets are available?
  • Summary

The demand for collection classes is always constant. Therefore, whether it is 1.0 to 2.0 generics or 3.0 to 4.0 parallelism (the parallelism in this Article refers to Concurrent, non-Parallel ),.. NET each version is always accompanied by the growth of some collection classes. As parallel computing is becoming increasingly popular, I will give a brief introduction to the namespace System. Collections. Concurrent added in. NET 4.0 and Its classes below.

Why Concurrent?

I believe many of my friends have had multi-threaded programming experience. However, before. NET 4.0, multi-threaded programming was prone to problems. Let's look at a simple example first.

Code

 static void main()
{
myList = new List<string>();
for (int i = 0; i < 1000; i++)
{
myList.Add(i.ToString());
}
new Thread(T2).Start();
new Thread(T3).Start();
}

static IList<string> myList;
static void T2()
{
Thread.Sleep(100);
for (int i = 0; i < 50; i++)
{
myList.Remove(i.ToString());
}
}
static void T3()
{
foreach (var a in myList)
{
Console.WriteLine(a);
}
}

 

In this example, we first Initialize an array with a length of 1000, and then start two threads, one for deletion and the other for simple read operations. If you run the code, you will find that the program will throw InvalidOperationException, because the system set is modified while being read, so the listing operation may not be executed.

Of course, we had a way to avoid such similar operations before 4.0. For example, we can lock the objects to be operated. That is, we can add code lock (myList) to the myList set before performing read/write operations ).

However, this method is not concise enough, and it may seem complicated in more complex cases. At this time, the set supporting parallel operations came into being.

What Concurrent sets are available?

In System. collections. there are not many classes exposed by Concurrent, they exist in two different dll, where in System. only one BlockingCollection <T> and ConcurrentBag <T> In the dll. dll is slightly more, they are ConcurrentQueue <T>, ConcurrentStack <T>, ConcurrentDictionary <TKey, TValue>. But for daily development, they are basically enough. Let's take a look at the construction of these classes one by one.

First, let's take a look at several classes in mscorlib. NET 2.0 has been exposed to their normal versions, so their functions remain unchanged. Therefore, you can still use normal version hash tables, queues, and stacks as before.

However, the parallel class not only converts the previous collection class into a thread-safe parallel class, but also provides some richer functions. Due to the introduction of Lamda expressions, the ConcurrentDictionary <TKey, TValue> you can use AddOrUpdate or GetOrAdd to add your own value generation scheme. This makes it easier and easier to generate key-value pairs. For example:

Code

 ConcurrentDictionary<int, string> td = new ConcurrentDictionary<int, string>();
Func<int, string> genVar = (i) => i.ToString();
Task.Factory.StartNew(() =>
{
for (int i = 0; i < 1000; i++)
{
td.GetOrAdd(i, genVar);
}
});
Task.Factory.StartNew(() =>
{
Func<int, string, string> updateVar = (key, oldVar) => oldVar + key;
td.AddOrUpdate(0, genVar, updateVar);
Console.WriteLine(td[0]);
}).Wait();

 

We can see that if the hash table does not have this value, we can generate it by ourselves, or we can easily solve the problem if we encounter duplicate key values when adding new values. This method is more concise and convenient than the previous painful judgment when adding or searching data.

The usage of functions in other classes has not changed much. The only difference is that various try function operations are common in the Concurrent namespace.

Next let's look at the parallel set in System. dll. The two classes here are not available in the previous. NET. First, let's look at ConcurrentBag <T>. As the name suggests, this class provides the function of parallel data packets. This class is relatively simple to construct and inherits from four interfaces: IProducerConsumerCollection <T>, IEnumerable <T>, ICollection, and IEnumerable are familiar with the common interfaces of the next three collection classes. Due to the implementation of the IEnumerable <T> interface, ConcurrentBag <T> also supports the LINQ operation. However, there is a special interface IProducerConsumerCollection <T> which we have never seen before. Although it is a new interface, this interface provides a set of operations for producers and consumers, it provides four basic methods: CopyTo (T [], int), ToArray (), TryAdd (T), and TryTake (out T ). Here, we mainly focus on the following two methods. TryAdd is the add element operation, while TryTake is the get element operation. However, in ConcurrentBag, The TryAdd method is set to protected, and external objects need to be added through the Add operation. In addition to TryTake, we can also use TryPeek to retrieve the current last element of the set without deleting it. Let's take a look at the example below:

Code

 static void main()
{
ConcurrentBag<string> bag = new ConcurrentBag<string>();
Task.Factory.StartNew(() =>
{
for (int i = 0; i < 1000; i++)
{
bag.Add(i.ToString());
}
bag.Add("Last");
});

Task.Factory.StartNew(() =>
{
foreach (string item in bag)
{
Console.WriteLine(item);
}
}).Wait();
}

 

BlockingCollection <T> is relatively more complex. It implements four interfaces: IEnumerable <T>, ICollection, IEnumerable, and IDisposable. Therefore, this collection also supports LINQ, it also provides richer features than ConcurrentBag. Such as CompleteAdding and the TryAdd and TryTake methods for timeout settings.

Summary

With the increasing demand for multithreading and parallel programming, I believe that in the future ,. these classes added to the NET family will become more and more common in our daily programming life, so it is more and more necessary to master them.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.