Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8440933
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 10, 20262026-06-10T08:26:03+00:00 2026-06-10T08:26:03+00:00

I’m using a BlockingCollection to implement a producer/consumer pattern. I have an asynchronous loop

  • 0

I’m using a BlockingCollection to implement a producer/consumer pattern. I have an asynchronous loop that fills the collection with data to be processed which can then at a much later time be accessed by the client. The packets arrive sparsely and I would like the polling to be done without using a blocking call to take.

In essence, I’m looking for something like a BeginTake and EndTake that does not exist in the blocking collection so that I can make use of the internal thread pool in a callback. It does not have to be a BlockingCollection by any means. Anything that does what I need would be great.

This is what I’ve got now. _bufferedPackets is a BlockingCollection<byte[]>:

public byte[] Read(int timeout)
{
    byte[] result;
    if (_bufferedPackets.IsCompleted)
    {
        throw new Exception("Out of packets");
    }
    _bufferedPackets.TryTake(out result, timeout);      
    return result;
}

I’d like this to be something like this, in pseudocode:

public void Read(int timeout)
{
    _bufferedPackets.BeginTake(result =>
        {
            var bytes = _bufferedPackets.EndTake(result);
            // Process the bytes, or the resuting timeout
        }, timeout, _bufferedPackets);
}

What are my options for this? I do not want to place any thread in a waiting state, since there is lots of other IO stuff for it to process, and I would run out of threads pretty quickly.

Update: I’ve rewritten the code in question to use the async process differently, essentially swapping callbacks based on if there is a waiting request within the timeout limit. This works fine, but still it would be awesome if there was a way to do this without resorting to timers and swapping lambdas around which potentially causes race conditions and is hard to write (and understand). I have solved this also with an own implementation of an async queue, but it would still be awesome if there was a more standard and well tested option.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-10T08:26:04+00:00Added an answer on June 10, 2026 at 8:26 am

    So there doesn’t look to be a built in option for this, I went out and tried to do my best to make what I wanted as an experiment. Turns out there is a lot of cruft to do in order to make this work roughly as other users of the old async pattern.

    public class AsyncQueue<T>
    {
        private readonly ConcurrentQueue<T> queue;
        private readonly ConcurrentQueue<DequeueAsyncResult> dequeueQueue; 
    
        private class DequeueAsyncResult : IAsyncResult
        {
            public bool IsCompleted { get; set; }
            public WaitHandle AsyncWaitHandle { get; set; }
            public object AsyncState { get; set; }
            public bool CompletedSynchronously { get; set; }
            public T Result { get; set; }
    
            public AsyncCallback Callback { get; set; }
        }
    
        public AsyncQueue()
        {
            dequeueQueue = new ConcurrentQueue<DequeueAsyncResult>();
            queue = new ConcurrentQueue<T>();
        }
    
        public void Enqueue(T item)
        {
            DequeueAsyncResult asyncResult;
            while  (dequeueQueue.TryDequeue(out asyncResult))
            {
                if (!asyncResult.IsCompleted)
                {
                    asyncResult.IsCompleted = true;
                    asyncResult.Result = item;
    
                    ThreadPool.QueueUserWorkItem(state =>
                    {
                        if (asyncResult.Callback != null)
                        {
                            asyncResult.Callback(asyncResult);
                        }
                        else
                        {
                            ((EventWaitHandle) asyncResult.AsyncWaitHandle).Set();
                        }
                    });
                    return;
                }
            }
            queue.Enqueue(item);
        }
    
        public IAsyncResult BeginDequeue(int timeout, AsyncCallback callback, object state)
        {
            T result;
            if (queue.TryDequeue(out result))
            {
                var dequeueAsyncResult = new DequeueAsyncResult
                {
                    IsCompleted = true, 
                    AsyncWaitHandle = new EventWaitHandle(true, EventResetMode.ManualReset), 
                    AsyncState = state, 
                    CompletedSynchronously = true, 
                    Result = result
                };
                if (null != callback)
                {
                    callback(dequeueAsyncResult);
                }
                return dequeueAsyncResult;
            }
    
            var pendingResult = new DequeueAsyncResult
            {
                AsyncState = state, 
                IsCompleted = false, 
                AsyncWaitHandle = new EventWaitHandle(false, EventResetMode.ManualReset), 
                CompletedSynchronously = false,
                Callback = callback
            };
            dequeueQueue.Enqueue(pendingResult);
            Timer t = null;
            t = new Timer(_ =>
            {
                if (!pendingResult.IsCompleted)
                {
                    pendingResult.IsCompleted = true;
                    if (null != callback)
                    {
                        callback(pendingResult);
                    }
                    else
                    {
                        ((EventWaitHandle)pendingResult.AsyncWaitHandle).Set();
                    }
                }
                t.Dispose();
            }, new object(), timeout, Timeout.Infinite);
    
            return pendingResult;
        }
    
        public T EndDequeue(IAsyncResult result)
        {
            var dequeueResult = (DequeueAsyncResult) result;
            return dequeueResult.Result;
        }
    }
    

    I’m not too sure about the synchronization of the IsComplete property, and I’m not too hot on how the dequeueQueue only gets cleaned up on subsequent Enqueue calls. I’m not sure when is the correct time to signal the wait handles either but this is the best solution that I’ve got so far.

    Please do not consider this production quality code by any means. I just wanted to show the general gist of how I got around to keeping all threads spinning without waiting locks. I’m sure this is full of all kinds of edge cases and bugs but it fulfills the requirements and I wanted to give something back to people who comes across the question.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I have a French site that I want to parse, but am running into
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I have thousands of HTML files to process using Groovy/Java and I need to
I am trying to loop through a bunch of documents I have to put
I have a .ini file as follows: [playlist] numberofentries=2 File1=http://87.230.82.17:80 Title1=(#1 - 365/1400) Example
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have just tried to save a simple *.rtf file with some websites and

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.