How long is a single spin in ManualResetEventSlim

后端 未结 2 811
情书的邮戳
情书的邮戳 2020-12-30 05:59

How long is a single spin in c#? What I want to know is there is a ManualResetEventSlim that has a spinCount parameter and I want to know how long each spin is in millisecon

2条回答
  •  猫巷女王i
    2020-12-30 06:53

    There is no correlation between spinCount parameter in the constructor and the number of milliseconds spent doing a spin wait.

    Here is how it works. MRES uses this spinCount parameter to go through its own waiting routine independent of Thread.SpinWait.

    • The first 10 iterations alternate between calling Thread.Yield and Thread.SpinWait. The call to Thread.SpinWait starts with a spin of Environment.ProcessorCount * 4 and then approximately doubles on each successive call.
    • Thereafter each iteration divisible by 20 calls Thread.Sleep(1).
    • Otherwise those divisible by 5 call Thread.Sleep(0).
    • Otherwise Thread.Yield is called.
    • The CancellationToken is checked every 10 iterations after 100.

    So as you can see there is a fairly complex song-and-dance going on inside MRES's custom spinning routine. And the algorithm could change from version to version. There is really no way to predict how long each spin will last.

    If your typical wait times are 2-10 seconds then your code is almost certainly going to do a kernel level wait via Monitor.Wait and Monitor.Pulse coordinations because the spinCount parameter is limited to 2047 anyway.

    Plus, 2-10 seconds is a long time. Do you really want to spin that long?

提交回复
热议问题