Search code examples
c#multithreadingeventsautoresetevent

Can a blocked thread fire events?


I have a program that spawns a thread controlling a serial communication. While it waits for response on the serial port, I block the thread with a AutoResetEvent.

Will that thread be unable to execute the event when data is received because it is blocked?

To illustrate the point I have a simple version of my code below. Will this code result in a deadlock or can an event run in a blocked thread, eventually waking up itself?

AutoResetEvent rxDataReady = new AutoResetEvent(false);

public void GetSomeDataFromSerialPort()
{
    SerialPort sp = new SerialPort()
    sp.Write(dataRequest)

    rxDataReady.WaitOne();

    // Process data
}

private void ReadDataEventHandler(object sender, SerialDataReceivedEventArgs e)
{
    // Prepare data
    rxDataReady.Set();
}

Thank you very much


Solution

  • The remarks from MSDN SerialPort.DataReceived

    The DataReceived event is raised on a secondary thread when data is received from the SerialPort object

    So I don't think your code sample will end up deadlocking.

    However, the answer to your question in the title:

    Can a blocked thread fire events?

    No.