[英]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
.事件处理程序应在可用时读取串行数据并将其返回给函数
request
。 And after that the request
should request new data.之后,
request
应该请求新数据。 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.但我不明白如何让线程等待事件处理程序完成并将 bool
request
设置回 false 以便发送新请求。
According to your provided code fragment, pfcDataRequested
is a member of the class.根据您提供的代码片段,
pfcDataRequested
是该类的成员。 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.因此,在您的情况下,您“只需要”以某种方式修改
readSerialIn
回调方法,即在方法结束时,成员pfcDataRequested
再次设置为 false。
Like pfcDataRequested = false
.像
pfcDataRequested = false
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.