Xin vui lòng xem bên dưới mã giảcổ điển mô hình sản xuất tiêu dùng sử dụng blockingcollection và nhiệm vụ net 4 TPL
//Single or multiple Producers produce using below method
void Produce(object itemToQueue)
{
concurrentQueue.enqueue(itemToQueue);
consumerSignal.set;
}
//somewhere else we have started a consumer like this
//we have only one consumer
void StartConsumer()
{
while (!concurrentQueue.IsEmpty())
{
if (concurrentQueue.TrydeQueue(out item))
{
//long running processing of item
}
}
consumerSignal.WaitOne();
}
Làm thế nào để cổng mô hình này tôi đã sử dụng từ thời xa xưa để sử dụng nhiệm vụ tạo taskfactory và các tính năng truyền tín hiệu mới net 4. Nói cách khác, nếu ai đó viết mẫu này bằng cách sử dụng net 4 thì nó trông như thế nào? Mã giả là tốt. Iam đã sử dụng .net 4 concurrentQueue như bạn có thể thấy. Làm cách nào để sử dụng tác vụ và có thể sử dụng một số cơ chế báo hiệu mới hơn nếu có thể. cảm ơn
Giải pháp cho vấn đề của tôi bên dưới nhờ Jon/Dan. Ngọt. Không nhãn hiệu hoặc while (true) hoặc while (itemstoProcess) gõ vòng như ngày xưa
//Single or multiple Producers produce using below method
void Produce(object itemToQueue)
{
blockingCollection.add(item);
}
//somewhere else we have started a consumer like this
//this supports multiple consumers !
task(StartConsuming()).Start;
void StartConsuming()
{
foreach (object item in blockingCollection.GetConsumingEnumerable())
{
//long running processing of item
}
}
cancellations are handled using cancel tokens
Một lời giải thích và ví dụ thực sự tốt (vì nó từng bước) [có thể tìm thấy tại đây] (http://www.codethinked.com/blockingcollection-and-iproducerconsumercollection). – MajesticRa
Xin chào Gullu, xin hãy xem [mã này] (https://stackoverflow.com/questions/733793/implementing-the-producer-consumer-pattern-in-c-sharp/47179576#47179576). Đây là một ví dụ làm việc đơn giản về cách sử dụng một BlockingCollection cho các mẫu nhà sản xuất-người tiêu dùng. –