Exemplo n.º 1
0
        public void InterlockedTest(Sandbox sb)
        {
            int x = 0;
            // 迭代次数为500万
            const int iterationNumber = 5000000;
            // 不采用锁的情况
            // StartNew方法 对新的 Stopwatch 实例进行初始化,将运行时间属性设置为零,然后开始测量运行时间。
            Stopwatch sw = Stopwatch.StartNew();
            for (int i = 0; i < iterationNumber; i++)
            {
                x++;
            }

            StringBuilder s1 = new StringBuilder();
            sb.textBlock1.Text += s1.AppendFormat("Common increment,time is :{0} ms \t\n", sw.ElapsedMilliseconds).ToString();

            sw.Reset();
            sw.Start();
            x = 0;
            // 使用锁的情况, Interlocked提供多种线程安全的常用函数,如加减,交换,比较并交换等。
            // 这些操作都是原子操作 atomic operation
            for (int i = 0; i < iterationNumber; i++)
            {
                Interlocked.Increment(ref x);
            }
            s1.Clear();
            sb.textBlock1.Text += s1.AppendFormat("Interlocked increment,time is :{0} ms \t\n", sw.ElapsedMilliseconds).ToString();
        }
Exemplo n.º 2
0
 public void MultiThreadTest(Sandbox sb)
 {
     for (int i = 0; i < 20; i++)
     {
         Thread testThread = new Thread(ThreadAddFunc);
         testThread.Start(sb);
     }
 }