One possible solution would be to never leave the thread, which might be okey if you just need a short sleep. Just setup a while loop and check if wanted time has passed etc.
But this requires some way to make a section atomic. Does anyone know any way to do this in .NET?
Given that the timespan required is short, and that it is time sensitive, I'd say that passing out to another thread is not the correct approach. The second you give up a thread's processing to other system resources and threads, you can never guarantee getting the resources allocated back to your thread in the required time. So you're going to have to write some kind of loop. I did a few trials and even that is sketchy... I used to have a high speed timer function for measuring performance of components and functions, but I appear to have mislaid it. It relied on Win32/API programming, so it's not fabulously easy to understand.
I found another route: The System.Diagnostics.StopWatch... I just ran this block of code for a few minutes to test and it appears as though it's working... I can't guarantee it will always work, but it seems reasonably stable under a relatively normal load (i.e. my iTunes, 5 instances of Visual Studio Enterprise Edition, SQL Server 2005 under a usual every day load, Email, Excel, A couple of instances of Notepad, 2 screens).
-
Dim oStopWatch As New System.Diagnostics.Stopwatch()
-
While True
-
Dim StartTime As DateTime = Now()
-
Console.WriteLine("Start: " & StartTime)
-
oStopWatch.Start()
-
While oStopWatch.ElapsedMilliseconds < 10
-
'Do Nothing
-
End While
-
If oStopWatch.ElapsedMilliseconds <> 10 Then
-
Console.WriteLine("Failed")
-
End If
-
End While