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()
.
I used Invoke to fill txtInfo
it works ok, but not working with 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];
}
}
What should I do, any suggestions?
CodePudding user response:
I don't have the full context but hope that helps: if you are changing the value of any field or variable which is bound with the UI, should be done by using the UI Thread (Dispatcher), otherwise this may crash if other thread different than Dispatcher one tries to update it.
What I come up with is that Invoke()
method is executing the action asynchronously. So when mbRcvDataMngr()
is called there is a concurrency issue. You could try to ensure that invoked action is awaited, then when task is continuated, response has already been processed.