Adrian
Adrian

Reputation: 407

.NET DateTime object not very accurate?

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 response 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

Upvotes: 2

Views: 276

Answers (5)

Adrian
Adrian

Reputation: 407

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.

Upvotes: 0

Kees C. Bakker
Kees C. Bakker

Reputation: 33381

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.

Upvotes: 0

JYelton
JYelton

Reputation: 36512

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

Upvotes: 2

jason
jason

Reputation: 241601

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

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

Upvotes: 1

Chris B. Behrens
Chris B. Behrens

Reputation: 6295

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).

Upvotes: 0

Related Questions