0

Inspired by this https://stackoverflow.com/a/5852926/291415, I made a FixedSizeQueue that will empty itself when it reaches the configured size. And it will trigger an event at the time.

public new void Enqueue( T obj )
{
    base.Enqueue( obj );
    lock ( syncObject )
    {
        if ( base.Count > Size )
        {
            for ( int i = 0; i < Size; i++ )
            {
                T outObj;
                base.TryDequeue( out outObj );
                ItemsList.Add( outObj );
            }
            OnExportItems( new ExportEventArgs<T>( ItemsList ) );
            ResetItemsList();
        }
    }
}

And this works just fine.

But there is a case when the number of items queued is smaller than the size of the queue.

How should I flush the queue in this case? A timer that checks the queue every x milliseconds and triggers the emptying?

Community
  • 1
  • 1
bdaniel7
  • 197
  • 1
  • 10
  • `Queue.Clear()` Method? – Smartis has left SO again Apr 11 '17 at 11:18
  • 4
    What prevents your event handler from causing a deadlock? (Hint: it's luck.) – Eric Lippert Apr 11 '17 at 11:18
  • I don't know why code is so complicated. I just use a list object and use RemoveAt(0) method. – jdweng Apr 11 '17 at 11:47
  • I didn't mean what method of the collection, but what mechanism, what way. Currently I'm using a timer that calls a flush method. But I was hoping for a more elegant way. – bdaniel7 Apr 12 '17 at 08:06
  • @Eric Lippert: The lock will prevent the deadlock, I think? – bdaniel7 Apr 12 '17 at 08:10
  • 2
    Don't think; know. My advice is that you stop writing multithreaded code until after you understand the basics. How can a lock *prevent* a deadlock? That makes no sense. – Eric Lippert Apr 12 '17 at 08:23
  • 1
    Suppose thread A obtains the lock on the queue, Q. We context switch to thread B, which executes operation X; X takes monitor M and then attempts to enqueue, so thread B blocks on Q. Now we switch back to thread A which invokes your arbitrary event handler. The arbitrary event handler can do *anything*, including operation X. Suppose it does. It blocks attempting to obtain M. Now we have thread A blocked on M and thread B blocked on Q, and no ability to make progress on either thread. **What, other than luck, prevents this from happening in your program?** – Eric Lippert Apr 12 '17 at 08:30
  • I see what you mean. The event handler will not execute any call to Enqueue() or other queue method. – bdaniel7 Apr 12 '17 at 12:46

0 Answers0