I have never used SpinWait. I am waiting for a lockfile to be free, so we can lock the file with below code (FileShare.None)
This lockfile will always be avaliable in approx. <= 50 milliseconds.

I will be needed to react as fast as possible so I beleive it will be better to use .SpinWait rather than Thread.Sleep(1) as I do now.

I wonder how an accurate use of SpinWait would work in this scenario, to react as fast as possible to be able to lock the file?

            String lockfile = "C:/lockfile.txt"; FileStream fs = null;
            while (true)
                    //Try to Lock file                                                   
                    fs = new FileStream(lockFile, FileMode.Open, FileAccess.Read, FileShare.None);
                catch { Thread.Sleep(1); }


Spinwait is horrible and it should never be used. Even Microsoft say it's not useful for ordinary applications.

If you're going to use SpinWait, don't even bother waiting at all. You may as well just iterate your loop repeatedly until you get the result you want.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.21 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.