how to suspend a thread for 1 ms?

后端 未结 2 594
轻奢々
轻奢々 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?

提交回复
热议问题