Need an alternative method to get a resolution cycle of 20 milliseconds

I need to read a message from the network CANevery 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, 18msmy 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.

+4
5

20 Timer_Elpased. 15-20 . Thread.Sleep(20)

+1

, , .

, CANLL.

, .

0

Thread.Sleep :

  • : MSDN: . , # pinvoke.net.

  • Stopwatch . "", 1 .

  • , Thread

  • , .

  • : Thread.Sleep 1 , . Thread.SpinWait .

1. 2. , , /.

0

Source: https://habr.com/ru/post/1614286/


All Articles