簡體   English   中英

C#如何將數據從事件處理程序返回到線程

[英]C# how to return data from a eventhandler to a thread

以下函數在我的應用程序中作為線程運行。 我的函數從串行設備請求數據。 我將此代碼用於我的任務:

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;
                }
            }
        }
    }
}

事件處理程序應在可用時讀取串行數據並將其返回給函數request 之后, request應該請求新數據。 但我不明白如何讓線程等待事件處理程序完成並將 bool request設置回 false 以便發送新請求。

根據您提供的代碼片段, pfcDataRequested是該類的成員。 因此,在您的情況下,您“只需要”以某種方式修改readSerialIn回調方法,即在方法結束時,成員pfcDataRequested再次設置為 false。

pfcDataRequested = false

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM