Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How long is a single spin in ManualResetEventSlim

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 milliseconds or how it works? I know spinning is more efficient for short waits than a kernel wait. So I am just trying to see what I should set this value to for a job that generally takes 2-10 sec.

like image 636
kyleb Avatar asked Apr 24 '12 19:04

kyleb


1 Answers

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?

like image 155
Brian Gideon Avatar answered Oct 13 '22 22:10

Brian Gideon