none
ConcurrentQueue and throtting and time frame RRS feed

  • Question

  • I have a time window of X seconds.

    and amount of Y object;

    is there a way to remove in every X seconds Y objects from the ConcurrentQueue ?

    or if there are more then Y messages then remove it even before the time window of X seconds?

    Thursday, June 13, 2019 6:54 AM

All replies

  • Hi want 2 Learn,

    Thank you for posting here.

    Based on your description, you want to remove Y objects before the time window of X seconds.

    You could try the following code.

    private void Button1_Click(object sender, EventArgs e)
            {
    
                ConcurrentQueue<int> cq = new ConcurrentQueue<int>();
    
                // Populate the queue.
                for (int i = 0; i < 10000; i++)
                {
                    cq.Enqueue(i);
                }
                timer1.Interval = 1000;
                timer1.Start();
                for (int i = 0; i < 9900; i++)
                {
                    cq.TryDequeue(out i);
                }
                timer1.Stop();
    
                foreach (var item in cq)
                {
                    Console.WriteLine(item);
                }
            }

    Best Regards,

    Jack


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Thursday, June 13, 2019 8:19 AM
    Moderator
  • I tried it

    the loop run until the end

    just put in interval the value=1

    and you will see the result is not correct

    (I inserted into  the ! 100000 objects

    which take more then 1 lmiliseconds

    Thursday, June 13, 2019 2:02 PM
  • It's hardly fair to say "the result is not correct", when you didn't say what the result should be.  Your specification is not at all clear.  What do you want to happen if it takes longer than X seconds to process the messages?  Should the processing repeat?  How often?  As you have written it, it says you want to process all of the messages every X seconds.  Well, if you set a time limit of 1ms but restart the processing every 1ms, then your process will run continuously.  There's no point to the timing.

    You can certainly limit a loop to a certain number of seconds by watching the tick count:

           int limit = 1000; // milliseconds
           long end = DateTime.Now.Ticks + limit * 10000;
           while( 
               DateTime.Now.Ticks < end
               &&
               !cq.IsEmpty()
           )
           {
               cq.TryDequeue( out j );
           }
    


    Tim Roberts | Driver MVP Emeritus | Providenza &amp; Boekelheide, Inc.

    Friday, June 14, 2019 6:43 PM