PDA

View Full Version : کلکشن‌هایی که به طور موازی کار میکنن چطور پیاده سازی شدند ؟



mr AHR
شنبه 04 آذر 1391, 09:05 صبح
سوال رو که گفتم .
من به یه کد نمونه
یه ارجاع تر و تمیز هم قانعم
ولی فقط من رو به کتاب های کت و کلفت ارجاع ندین
ممنون میشم

tooraj_azizi_1035
یک شنبه 17 دی 1391, 14:35 عصر
سناریوی تولیدکننده-مصرف کننده:

// A bounded collection. It can hold no more
// than 100 items at once.
BlockingCollection<Data> dataItems = new BlockingCollection<Data>(100);


// A simple blocking consumer with no cancellation.
Task.Run(() =>
{
while (!dataItems.IsCompleted)
{

Data data = null;
// Blocks if number.Count == 0
// IOE means that Take() was called on a completed collection.
// Some other thread can call CompleteAdding after we pass the
// IsCompleted check but before we call Take.
// In this example, we can simply catch the exception since the
// loop will break on the next iteration.
try
{
data = dataItems.Take();
}
catch (InvalidOperationException) { }

if (data != null)
{
Process(data);
}
}
Console.WriteLine("\r\nNo more items to take.");
});

// A simple blocking producer with no cancellation.
Task.Run(() =>
{
while (moreItemsToAdd)
{
Data data = GetData();
// Blocks if numbers.Count == dataItems.BoundedCapacity
dataItems.Add(data);
}
// Let consumer know we are done.
dataItems.CompleteAdding();
});