C# 线程问题,我无法正常工作,在 Events_DataReceived 中调用
C# thread issue, I can't function is not working correct which is called in Events_DataReceived
private void Events_DataReceived(object sender, DataReceivedFromServerEventArgs e)
{
try
{
this.Invoke((MethodInvoker)delegate
{
txtInfo.Text += $"Server: {BitConverter.ToString(e.Data)}{Environment.NewLine}";
tcp2rtu_Response(e.Data); // TODO: Test et.
});
mbRcvDataMngr();
}
catch (InvalidOperationException exc)
{
MessageBox.Show(exc.ToString());
}
catch (Exception exception)
{
MessageBox.Show(exception.Message);
}
}
The method I wrote tcp2rtu_Response()
, is for parsing e.Data
and filling public byte [] ReceiveBuffer
. But it's not filling the ReceiveBuffer[]
and not turning back to mbRcvDataMngr()
method, in Events_DataReceived()
.
我使用 Invoke 来填充 txtInfo
它工作正常,但不适用于 tcp2rtu_Response()
。
public void tcp2rtu_Response(byte[] tcpReceived)
{
ReceiveBuffer[0] = tcpReceived[6];
ReceiveBuffer[1] = tcpReceived[7];
for(int i = 8; i <= tcpReceived.Length; i++)
{
ReceiveBuffer[i - 6] = tcpReceived[i];
}
}
我该怎么办,有什么建议吗?
我没有完整的上下文,但希望对您有所帮助:如果您要更改与 UI 绑定的任何字段或变量的值,应使用 UI ] 线程(Dispatcher),否则如果不同于 Dispatcher 的其他线程尝试更新它,这可能会崩溃。
我想到的是 Invoke()
方法正在异步执行操作。因此,当 mbRcvDataMngr()
被调用时,存在并发问题。您可以尝试确保等待调用的操作,然后当任务继续时,响应已经被处理。
private void Events_DataReceived(object sender, DataReceivedFromServerEventArgs e)
{
try
{
this.Invoke((MethodInvoker)delegate
{
txtInfo.Text += $"Server: {BitConverter.ToString(e.Data)}{Environment.NewLine}";
tcp2rtu_Response(e.Data); // TODO: Test et.
});
mbRcvDataMngr();
}
catch (InvalidOperationException exc)
{
MessageBox.Show(exc.ToString());
}
catch (Exception exception)
{
MessageBox.Show(exception.Message);
}
}
The method I wrote
tcp2rtu_Response()
, is for parsinge.Data
and fillingpublic byte [] ReceiveBuffer
. But it's not filling theReceiveBuffer[]
and not turning back tombRcvDataMngr()
method, inEvents_DataReceived()
.
我使用 Invoke 来填充 txtInfo
它工作正常,但不适用于 tcp2rtu_Response()
。
public void tcp2rtu_Response(byte[] tcpReceived)
{
ReceiveBuffer[0] = tcpReceived[6];
ReceiveBuffer[1] = tcpReceived[7];
for(int i = 8; i <= tcpReceived.Length; i++)
{
ReceiveBuffer[i - 6] = tcpReceived[i];
}
}
我该怎么办,有什么建议吗?
我没有完整的上下文,但希望对您有所帮助:如果您要更改与 UI 绑定的任何字段或变量的值,应使用 UI ] 线程(Dispatcher),否则如果不同于 Dispatcher 的其他线程尝试更新它,这可能会崩溃。
我想到的是 Invoke()
方法正在异步执行操作。因此,当 mbRcvDataMngr()
被调用时,存在并发问题。您可以尝试确保等待调用的操作,然后当任务继续时,响应已经被处理。