Repeated use of AutoResetEvent

195 Views Asked by At

I'm new to multi-threading and I'm to understand how the AutoResetEvent works.

I'm trying to implement an optimization process where I'm sending data between two different softwares and I'm using two threads: the Main thread where I'm modifying and sending information and a Receiving Thread, always running in the background, waiting to catch the message with the results from the Sent Info. To implement that, after a message is sent, I want the main thread to wait until the receiver thread receives back the result and triggers the event that allows the main thread to continue where it left off.

Here is a simplified version of my code:

 // Thread 1 - MAIN

    static AutoResetEvent waitHandle = new AutoResetEvent(false);

    void foo()
    {
        for (int i = 0; i < 5; i++)
        {
            // ... Modify sendInfo data

            // Send data to other software
            SendData(sendInfo);

            // Wait for other software to process data and send back the result
            waitHandle.WaitOne();

            // Print Result
            print(receivedData);

            // Reset AutoResetEvent
            waitHandle.Reset();
        }
    }


    /////////////////////////////

    // Thread 2 - Receiver thread (running in the background)

    private event EventHandler MessageReceived;

    // ... Code for triggerring MessageReceived event each time a message is received

    private static void OnMessageReceived(object sender, EventArgs e)
    {
        waitHandle.Set();
    }

My question is:

Can you repeatedly use an AutoResetEvent in a loop like this? Am I using it correctly?

I'm pretty sure my send/receive loop is working properly, with the MessageReceived event succesfully triggered shortly after the sent message. But while my code works fine for a single iteration, it gets stuck on multiple iterations and I'm not sure why. Any suggestions?

0

There are 0 best solutions below