Spin 在 Portable Class Library 中等待多次旋转

Spinwait for a number of spins in Portable Class Library

我想通过 Xamarin 替换 PCL 中针对 ASPNET Core、.NET 4.5.2 和 Android+iOS 的 SpinWait 方法,但找不到直接等效。目前我正在考虑更换

System.Threading.Thread.SpinWait(10);

SpinWait spinWait = new SpinWait();
SpinWait.SpinUntil(() => spinWait.Count >= 10);

但我不知道我这样做是不是打开了一罐蠕虫。或者如果可能

for(int i=0; i<10; i++) SpinOnce();

更好。我已经避免了这种情况,因为每次旋转后 SpinOnce() 都会产生,因此效率似乎较低。

上下文:

我目前正在将此高精度计时器移植到 PCL(ASPNET Core、.NET 4.5.2 和 Android+iOS,通过 Xamarin)并即将推出针对 SpinWait 方法删除的问题。 http://www.codeproject.com/Articles/98346/Microsecond-and-Millisecond-NET-Timer

在 .NET Framework 中有一个 SpinWait() 方法,它接受一个 int,它指示等待多少次旋转 (https://msdn.microsoft.com/en-us/library/system.threading.thread.spinwait(v=vs.110).aspx) but the System.Threading.Thread namespace isn't available when targeting this combination of frameworks but does include a SpinWait struct (https://msdn.microsoft.com/en-us/library/system.threading.spinwait(v=vs.110).aspx) 这让我可以访问 SpinOnce() 和一个接受布尔返回函数的 SpinUntil() 方法。

原来我关于避免屈服的直觉并不完全正确,并且发现在 SpinUntil (http://referencesource.microsoft.com/#mscorlib/system/threading/SpinWait.cs) 的源代码中实际上重复调用了 SpinOnce()。

如果没有错误检查逻辑,它看起来像这样:

//Error Checking Logic
SpinWait spinner = new SpinWait();
        while (!condition())
        {
            //Timeout checks
            spinner.SpinOnce();
            //Timeout and Yielding checks
            }
        }
//Return Logic

因此,我将此作为一个可接受的实施示例,并将使用(除非出现更好的解决方案)类似于下面的内容来重新创建所需的行为。

SpinWait spinner = new SpinWait();
    while (spinner.Count<10)
    {
        spinner.SpinOnce();
        //Timeout and Yielding checks
        }
    }