I need to read a message from the network CAN
every 20ms
. To do this, I created a function that works below. It is a kind of work around, but it does work.
public void Read_CAN_RC_Message()
{
bool a = true;
while (a)
{
Stopwatch t = Stopwatch.StartNew();
// My actual Function Starts Here
int rMulti = CANbus.CAN_Receive_multiple_nonblock(recieveMsg, 5);
if (0 < rMulti)
{
count++;
for (int k = 0; k < rMulti; k++)
{
if (recieveMsg[k].id == 0x400)
{
currentX = 0;
currentY = 0;
currentX = currentX | recieveMsg[k].data[3];
currentX = (currentX << 8) | recieveMsg[k].data[2];
currentX = (currentX << 8) | recieveMsg[k].data[1];
currentX = (currentX << 8) | recieveMsg[k].data[0];
currentY = currentY | recieveMsg[k].data[7];
currentY = (currentY << 8) | recieveMsg[k].data[6];
currentY = (currentY << 8) | recieveMsg[k].data[5];
currentY = (currentY << 8) | recieveMsg[k].data[4];
}
// Function Ends here
int timestep = t.Elapsed.Milliseconds; // To measure Time Needded to complete the Operation
timeCheck.Rows.Add(timestep,str);
}
while (t.Elapsed < timer20ms)
{
// Nothing
}
}
}
Soon, I realized that it took an operation to complete 2ms
, but for the rest, 18ms
my processor got stuck in an infinite loop. Therefore, this operation requires a separate separate thread, which always works (using the processor). Is there a tidier more professional way to do this. Please suggest. I need to run this application in a separate thread, since it should always start as soon as the application starts until it shuts down.