C# 线程问题,我无法正常工作,在 Events_DataReceived 中调用
Posted
技术标签:
【中文标题】C# 线程问题,我无法正常工作,在 Events_DataReceived 中调用【英文标题】:C# thread issue, I can't function is not working correct which is called in Events_DataReceived 【发布时间】:2021-12-23 21:54:28 【问题描述】: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);
我写
tcp2rtu_Response()
的方法是解析e.Data
,填充public byte [] ReceiveBuffer
。但它没有填充ReceiveBuffer[]
,也没有回到mbRcvDataMngr()
方法,在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];
我该怎么办,有什么建议吗?
【问题讨论】:
能否请您提供有关您遇到的错误的更多信息? :) 【参考方案1】:我没有完整的上下文,但希望对您有所帮助:如果您要更改与 UI 绑定的任何字段或变量的值,则应使用 UI 线程(调度程序)来完成,否则可能会崩溃如果不同于 Dispatcher 的其他线程尝试更新它。
我想出的是Invoke()
方法正在异步执行操作。因此,当调用 mbRcvDataMngr()
时会出现并发问题。您可以尝试确保等待调用的操作,然后当任务继续时,响应已经被处理。
【讨论】:
感谢关注。我已经解决了这个问题。实际上,这只是 for 循环条件错误。就这样解决了。for (int i = 8; i < tcpReceived.Length; i++)
以上是关于C# 线程问题,我无法正常工作,在 Events_DataReceived 中调用的主要内容,如果未能解决你的问题,请参考以下文章