How to remove a new item from a queue in a queue

I have an application that works with a queue with strings (which corresponds to the various tasks that the application must perform). In random moments, the queue can be filled with lines (sometimes several times per minute, but it can also take several hours.

Until now, I always had a timer that checked every few seconds to see if there were any items in the queue and deleted them.

I think there should be a nicer solution than this path. Is there a way to get an event or so when an item is added to the queue?

+4
source share
3 answers

. TPL, , BufferBlock<T>, , BlockingCollection , async/await.

, :

void Main()
{
    var b = new BufferBlock<string>();
    AddToBlockAsync(b);
    ReadFromBlockAsync(b);
}

public async Task AddToBlockAsync(BufferBlock<string> b)
{
    while (true)
    {
        b.Post("hello");
        await Task.Delay(1000);
    }
}

public async Task ReadFromBlockAsync(BufferBlock<string> b)
{
    await Task.Delay(10000); //let some messages buffer up...
    while(true)
    {
        var msg = await b.ReceiveAsync();
        Console.WriteLine(msg);
    }
}
+5

BlockingCollection.GetConsumingEnumerable. , , foreach.

, CancellationToken, , .

+2

BlockingCollection? GetConsumingEnumerable() , , , Thread.Sleep's:

//:

  BlockingCollection<string> _blockingCollection =
                     new BlockingCollection<string>();

//

 for (var i = 0; i < 100; i++) 
 {
    _blockingCollection.Add(i.ToString());
    Thread.Sleep(500); // So you can track the consumer synchronization. Remove.
 }

//:

   foreach (var item in _blockingCollection.GetConsumingEnumerable())
   {
      Debug.WriteLine(item);
   }
+1
source

Source: https://habr.com/ru/post/1543438/


All Articles