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 8163995
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 6, 20262026-06-06T19:12:14+00:00 2026-06-06T19:12:14+00:00

I’m creating a console application that should receive messages from the network in order

  • 0

I’m creating a console application that should receive messages from the network in order to process them. First I created a singleton class to ensure that the same queue is accessible by all classes: this class is ProcessingQueue.

public class ProcessingQueue
{
    public class ItemToProcess
    {
        public string SourceClientId { get; set; }
        public IMessage ReceivedMessage { get; set; }
    }

    private int m_MaxSize = 20;
    private Queue<ItemToProcess> m_InternalQueue;

    private static volatile ProcessingQueue m_Instance = null;
    private static readonly object syncRoot = new object();

    private ProcessingQueue()
    {
        m_InternalQueue = new Queue<ItemToProcess>();
    }

    public static ProcessingQueue Instance
    {
        get
        {
            if (m_Instance == null)
            {
                lock (syncRoot)
                {
                    if (m_Instance == null)
                    {
                        m_Instance = new ProcessingQueue();
                    }
                }
            }
            return m_Instance;
        }
    }

    public int MaxSize
    {
        get
        {
            lock (syncRoot)
            {
                return m_MaxSize;
            }
        }
        set
        {
            if (value > 0)
            {
                lock (syncRoot)
                {
                    m_MaxSize = value;
                }
            }
        }
    }

    public void Enqueue(String source, IMessage message)
    {
        lock (syncRoot)
        {
            while (m_InternalQueue.Count >= m_MaxSize)
            {
                Monitor.Wait(syncRoot);
            }
            m_InternalQueue.Enqueue(new ItemToProcess { SourceClientId = source, ReceivedMessage = message });
            if (m_InternalQueue.Count == 1)
            {
                Monitor.PulseAll(syncRoot);
            }
        }
    }

    public ItemToProcess Dequeue()
    {
        lock (syncRoot)
        {
            while (m_InternalQueue.Count == 0)
            {
                Monitor.Wait(syncRoot);
            }
            ItemToProcess item = m_InternalQueue.Dequeue();
            if (m_InternalQueue.Count == m_MaxSize - 1)
            {
                Monitor.PulseAll(syncRoot);
            }
            return item;
        }
    }

    public int Count
    {
        get
        {
            lock (syncRoot)
            {
                return m_InternalQueue.Count;
            }
        }
    }
}

Then I implemented the main class of the project as follows.

  1. First of all, the shared queue is instantiated.
  2. Then I set a timer to simulate the arrival of a keep alive message (first producer).
  3. Then I created the consumer thread (processing object).
  4. Then I created another producer thread (generating object).
  5. Finally, I run all the threads and the timer.

    class Program
    {
    static ProcessingQueue queue = ProcessingQueue.Instance;
    static System.Timers.Timer keep_alive_timer = new System.Timers.Timer(10000);

    private static volatile bool running = true;
    
    
    static void Main(string[] args)
    {
        queue.MaxSize = 30;
        keep_alive_timer.Elapsed += new ElapsedEventHandler(delegate(object sender, ElapsedEventArgs e)
        {
            KeepAliveMessage msg = new KeepAliveMessage(Guid.NewGuid());
            Console.WriteLine("Keep Alive: " + msg.MsgId);
            queue.Enqueue("", msg);
        });
        keep_alive_timer.Enabled = true;
        keep_alive_timer.AutoReset = true;
    
        Thread processing = new Thread(delegate()
        {
            while (running)
            {
                Console.WriteLine("Number of elements in queue: {0}", queue.Count);
    
                ProcessingQueue.ItemToProcess msg = queue.Dequeue();
                Console.WriteLine("Processed: msgid={0}, source={1};", msg.ReceivedMessage.MsgId, msg.SourceClientId);
    
                Thread.Sleep(1500);
            }
        });
    
        Thread generating = new Thread(MessagesFromNetwork);
    
        processing.Start();
        keep_alive_timer.Start();
        generating.Start();
    
        Console.WriteLine("RUNNING...\n");
        Console.ReadLine();
    
        running = false;
        keep_alive_timer.Stop();
        Console.WriteLine("CLOSING...\n");
    
        //processing.Abort();
        //generating.Abort();
    
        bool b1 = processing.Join(TimeSpan.FromSeconds(5));
        bool b2 = generating.Join(TimeSpan.FromSeconds(5));
    
        Console.WriteLine("b1 {0}", b1);
        Console.WriteLine("b2 {0}", b2);
        Console.WriteLine("END");
        Console.ReadLine();
    }
    
    static void MessagesFromNetwork()
    {
        string[] sourceClients = { "1", "2", "3", "4", "5" };
        while (running)
        {
            IMessage msg; // interface IMessage
            Random random = new Random();
            int type = random.Next(2);
            switch (type)
            {
                case 0:
                    msg = new KeepAliveMessage(Guid.NewGuid());   // implements IMessage
                    break;
                case 1:
                    msg = new TaskMessage(Guid.NewGuid(), ...);   // implements IMessage
                    break;
                default:
                    throw new Exception("Messaggio non valido!");
            }
            Console.WriteLine("New message received: " + msg.MsgId);
            queue.Enqueue(sourceClients[random.Next(sourceClients.Length)], msg);
            Console.WriteLine("... message enqueued: " + msg.MsgId);
            Thread.Sleep(500);
        }
    }
    

    }

Pressing Enter during the execution, the running variable becomes false and both the thread should terminate. However this does not always happen, in fact one of the two methods Join did not return the control: for this reason I specified a timeout within the Join methods, but after Console.WriteLine("END"); the console application freezes (the second Join returns false).

Maybe the second thread is not terminated properly … Why?

  • 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-06T19:12:15+00:00Added an answer on June 6, 2026 at 7:12 pm

    Seems like Dequeue or Enqueue could go into a Monitor.Wait() , when running is stopped nobody is pulsed.

    You wait 5 seconds but note that MaxSize * 1500 > 5000

    I couldn’t so directly find out the Timer frequency.

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

Sidebar

Related Questions

I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
For some reason, after submitting a string like this Jack’s Spindle from a text
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I've got a string that has curly quotes in it. I'd like to replace
I have a French site that I want to parse, but am running into
I am doing a simple coin flipping experiment for class that involves flipping a
We're building an app, our first using Rails 3, and we're having to build
I have a text area in my form which accepts all possible characters from

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.