27 Eylül 2016 Salı

ConcurrentBag Sınıfı

Constructor
Şöyle yaparız.
ConcurrentBag<int> numbers = new ConcurrentBag<int>();
Add metodu
Şöyle yaparız.
int i = 0;
numbers.Add (i);
Contains metodu
Şöyle yaparız.
numbers.Contains (10000);
Enumeration
Bir thread ekleme yaparken, diğer enumeration yapabilir. Bu konuda SynchronizedCollection sınıfından üstündür.
var collection = new ConcurrentBag<int>();var n = 0;

Task.Run(() =>{
  while (true)
  {
    collection.Add(n++);
    Thread.Sleep(5);
  }
});

Task.Run(() =>{
  while (true)
  {
    Console.WriteLine("Elements in collection: " + collection.Count);

    var x = 0;
    if (collection.Count % 100 == 0)
    {
      foreach (var i in collection)
      {
        Console.WriteLine("They are: " + i);
        x++;
        if (x == 100)
        {
          break;
        }
      }
    }
  }
});

Console.ReadKey();
TryTake metodu
Şöyle yaparız.
int item;
if (numbers.TryTake (out item)) {...}

Hiç yorum yok:

Yorum Gönder