简体   繁体   中英

C# how to return data from a eventhandler to a thread

The following functions runs as thread in my application. My function requests data from a serial device. I use this code for my task:

private void request(ClsComSettingMain clsComSettingMain, CancellationToken token) //class for async data requests
{
    Console.WriteLine("Debug: Hello from serialTask.");

    string comPort = clsComSettingMain.comport;
    int baudRate = clsComSettingMain.baudRate;

    if (comPort != null && baudRate != 0)
    {
        SerialPort serialPort = new SerialPort(comPort, baudRate);
        serialPort.ReadTimeout = 200;
        serialPort.Open();
        serialPort.DataReceived += new SerialDataReceivedEventHandler(readSerialIn); //register for SerialDataReceivedEvent

        while (true)
        {
            if (token.IsCancellationRequested)
            {
                Console.WriteLine("Debug: Serialthread cancelled.");
                serialPort.Dispose(); // free all ressources for GC
                return;
            }
            else
            {
                if (!pfcDataRequested) //check if data is already requested
                {
                    Console.WriteLine("Debug: Requesting data from serial, send raw: 0xF0, 0x02, 0x0D");
                    serialPort.Write(adv_request, 0, 3); // Write byte array to serial port, with no offset, all 3 bytes
                    pfcDataRequested = true;
                }
            }
        }
    }
}

The eventhandler should read the serial data when available and returns it to the function request . And after that the request should request new data. But I don't understand how to make the thread wait for the eventhandler do finish and set the bool request back to false so a new request is send.

According to your provided code fragment, pfcDataRequested is a member of the class. So in your case you would "just" need to modify the readSerialIn callback method in a way, that at the end of the method the member pfcDataRequested is set to false again.

Like pfcDataRequested = false .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM