how to suspend a thread for 1 ms?

后端 未结 2 592
轻奢々
轻奢々 2021-01-24 03:07

I need prety simple thing

while (true) {
    DoJob();
    // wait 1 ms
}

Should I just use Thread.Sleep(1)? I\'m not sure about us

相关标签:
2条回答
  • 2021-01-24 03:39

    Edit -- corrected "most resolution you will get from sleep to about 20 ms, instead of 100 ms

    About the most resolution that you will get out of sleep is 100 milliseconds, even if you pass Sleep(1).

    For what it's worth, a timer may be more efficient for this -- especially if you have more than 1 thread sleeping (System.Threading.Timer will will use as few threads as it needs to if you allocate multiple timers, they will share a timing thread) (this from Joe Duffy's Concurrent Programming book)

    But more importantly, what are you trying to do? If you are polling -- need to wait for something to happen, you may be able to use a more efficient means of doing it. If you just need to fire off a task every so often, A timer is probably going to be your best bet.

    If you are only want to stop for a millisecond, may I ask why? Are you just trying to make sure that your thread yields to other processes?

    0 讨论(0)
  • 2021-01-24 03:43

    There may be an alternative way to do this. Windows has a high resolution timer. You can read about it here: "How to: Use the high resolution timer"

    I don't think that this works like a regular timer -- it doesn't fire off events, you just use it to measure how much time has passed with high precision. However, you could loop on it, and execute code when a Millisecond passes (you will be consuming CPU the whole time). Also, I agree with Henk's comments that Windows is not a realtime O/S -- you never know when the O/S will suspend your thread.

    0 讨论(0)
提交回复
热议问题