标签:i++ sea create mil ons font setevent bsp out
29.4.1 Event构造
class Program { static void Main() { int x = 0; const int iterations = 10000000; Stopwatch sw = Stopwatch.StartNew(); // 1 for (int i = 0; i < iterations; i++) { x++; } Console.WriteLine("incrementing x:{0:N0}", sw.ElapsedMilliseconds); // 2 sw.Restart(); for (int i = 0; i < iterations; i++) { M(); x++; M(); } Console.WriteLine("incrementing in M x:{0:N0}", sw.ElapsedMilliseconds); // 3 SpinLock s1 = new SpinLock(); sw.Restart(); for (int i = 0; i < iterations; i++) { bool taken = false; s1.Enter(ref taken); x++; s1.Exit(); } Console.WriteLine("incrementing in SpinLock x:{0:N0}", sw.ElapsedMilliseconds); // 4 using (SimpleWaitLock sw1 = new SimpleWaitLock()) { sw.Restart(); for (int i = 0; i < iterations; i++) { sw1.Enter(); x++; sw1.Leave(); } Console.WriteLine("incrementing x in SimpleWaitLock:{0:N0}", sw.ElapsedMilliseconds); } //incrementing x:44 //incrementing in M x:174 //incrementing in SpinLock x:3,186 //incrementing x in SimpleWaitLock: 33,481 Console.ReadKey(); //bool createdNew; //此代码 仅供看 //using (new Semaphore(0, 1, "SomeUniqueStringIdentifyingMyApp", out createdNew)) //{ //} } [MethodImpl(MethodImplOptions.NoInlining)] private static void M() { } } internal sealed class SimpleWaitLock : IDisposable { private readonly AutoResetEvent m_available; public SimpleWaitLock() { m_available = new AutoResetEvent(true); //最开始可自由使用 } public void Enter() { //在内核中阻塞,直到资源可用 m_available.WaitOne(); } public void Leave() { //让另一个线程访问资源 m_available.Set(); } public void Dispose() { m_available.Dispose(); } }
标签:i++ sea create mil ons font setevent bsp out
原文地址:https://www.cnblogs.com/kikyoqiang/p/10225194.html