开发者

.NET DateTime object not very accurate?

开发者 https://www.devze.com 2023-02-03 21:46 出处:网络
I am currently trying to write some code which is going to send a request to a device, and then wait for the response. The problem is the r开发者_开发技巧esponse does not have an end character to indi

I am currently trying to write some code which is going to send a request to a device, and then wait for the response. The problem is the r开发者_开发技巧esponse does not have an end character to indicate the message is complete so we just have to wait a period of time.

What I want to do is send the message and then wait a period of time. Each time a piece of data arrives I want to increment the period of time I am waiting by say another 100ms incase there is any more data to follow. If nothing comes in after that period it is assumed that the message is complete. This is the pseudo code I came up with:

var waitTime

Function SendData(data)
{
     send the request here and then block with the next code

     while (waitTime)
     {
          //wait
     }
}

Function RecieveData(data)
{
     Assign new data to a buffer
     waitTime++
}

The SendData and RecieveData functions are both on different threads within a class. I am coding this in C#. I have tried implementing this with a DataTime object, but it does not seem to be very accurate when working with 10's/100's of milliseconds?

Any advice on what would be the best way to implement this would be appreciated!

Regards Adrian


Consider using the stopwatch class to measure small increments such as this.


DateTime is accurate to approximately 1/64th of a second.

Why don't you just use System.Threading.Thread.Sleep(milliseconds)?


Try comparing DateTime.Ticks instead. A tick is 100 nanoseconds. It is as accurate as the system clock. Of course, the difference between two computers may be tremendous (comparitively).


If you want to sleep for a while, just use Thread.Sleep(10000) this causes the thread to sleep for the number of miliseconds you want.


Ok, just to end this question I thought I would post my solution:

bool dataInFlag;

function sendData(data)
{
     Send();

     dataInFlag = true;

     while(dataInFlag)
     {
           dataInFlag = false;
           Thread.Sleep(400);
     }
}

function recieveData(data)
{
     Parse();
     dataInFlag = true;
}

So in a nutshell, the while loop will execute, set the dataInFlag back to false and then sleep, if no data is received during the sleep the while loop will exit. If data is received the dataInFlag is set back to true and the loop will fire again! I have extended this so that the first execution of the while loop sleeps for a longer period, and each subsequent loop sleeps for a shorter period.

Thanks again for all the replies.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号