If a message queue is dequeued on an STAThread tagged method, is it good practice to ensure it is also enqueues on an STAThread tagged method?

29 views Asked by At

Right now I am in the middle of a thorny bug having to do with message queues and, what I suspect to be, something to do with the [STAThread] tag or lack thereof.

My application sends messages to a communication chip in the following manner:

private ConcurrentQueue<Byte[]> msgQueue;

MesssageHandlerConstructor()
{ 
    try
    {
        msgQueue = new ConcurrentQueue<Byte[]>();

        BackgroundWorker messageHandlerWorker = new BackgroundWorker();
        messageHandlerWorker.WorkerSupportCancellation = true;
        messageHandlerWorker.DoWork += manageMessages;
        messageHandlerWorker.RunWorkerAsync();
    }
    catch (Exception ex)
    {
        //irrelevant catch code
    }
}

...


[STAThread]
private void manageMessages(object sender, DoWorkEventArgs e)
{
    try
    {
        Byte[] message;
        
        while (!booleanToPreventCancellation)
        {
             if(!messageQueue.IsEmpty)
             {
                 msgQueue.TryDequeue(out message);

                 //some code to send a message to the chip
             }
        }
    }
    catch (Exception ex)
    {
        //irrelevant catch code
    }
}
    

Messages are added to the messageQueue in the following manner. Note this method is inside the same MessageHandler class.

private void QueueMessage(string Name, Byte[] data)
{
    try
    {
        msgQueue.Enqueue(data)
    }
    catch (Exception ex)
    {
        //irrelevant catch code
    }
}

My issue is that I have run into a situation where I properly enqueue a message, but the dequeuing returns the second most recent message that I enqueued, not the most recent one. This leads to my question:

If I am dequeuing messages with an [STAThread] method, must I also be enqueueing them in an [STAThread] method?

0

There are 0 answers