rt~~

解决方案 »

  1.   

    lock 确保当一个线程位于代码的临界区时,另一个线程不进入临界区。如果其他线程试图进入锁定的代码,则它将一直等待(即被阻止),直到该对象被释放。下例使用线程和 lock。只要 lock 语句存在,语句块就是临界区并且 balance 永远不会是负数。复制// statements_lock2.cs
    using System;
    using System.Threading;class Account
    {
        private Object thisLock = new Object();
        int balance;    Random r = new Random();    public Account(int initial)
        {
            balance = initial;
        }    int Withdraw(int amount)
        {        // This condition will never be true unless the lock statement
            // is commented out:
            if (balance < 0)
            {
                throw new Exception("Negative Balance");
            }        // Comment out the next line to see the effect of leaving out 
            // the lock keyword:
            lock(thisLock)
            {
                if (balance >= amount)
                {
                    Console.WriteLine("Balance before Withdrawal :  " + balance);
                    Console.WriteLine("Amount to Withdraw        : -" + amount);
                    balance = balance - amount;
                    Console.WriteLine("Balance after Withdrawal  :  " + balance);
                    return amount;
                }
                else
                {
                    return 0; // transaction rejected
                }
            }
        }    public void DoTransactions()
        {
            for (int i = 0; i < 100; i++)
            {
                Withdraw(r.Next(1, 100));
            }
        }
    }class Test
    {
        static void Main()
        {
            Thread[] threads = new Thread[10];
            Account acc = new Account(1000);
            for (int i = 0; i < 10; i++)
            {
                Thread t = new Thread(new ThreadStart(acc.DoTransactions));
                threads[i] = t;
            }
            for (int i = 0; i < 10; i++)
            {
                threads[i].Start();
            }
        }
    }
      

  2.   

    lock  主要用于锁定某一个值,保证在程序运行过程中,该变量的地址始终不会改变,除非人为释放或者重新创建在设计模式中用于 单例模式比较多,winform中全局变量的调用和复制时用的比较多
    webform中 对于缓存使用的比较多
      

  3.   

    我不是百度的
    比百度权威多了
    我的是MSDN