قفل بيان (C# مرجع)

The lock كلمة أساسية marks a كشف حظر كـ a حرج مقطع بواسطة obtaining the mutual-exclusion قفل for a given كائن, executing a كشف, و then releasing the قفل. This كشف takes the following نموذج:

Object thisLock = new Object();
lock (thisLock)
{
    // Critical code section.
}

لمزيد من المعلومات، راجع مؤشر الترابط تزامن (برمجة دليل C#).

ملاحظات

The lock كلمة أساسية ensures that واحد مؤشر ترابط does not Enter الزر a حرج مقطع of تعليمات برمجية while another مؤشر ترابط هو في the حرج مقطع. If another مؤشر ترابط tries إلى Enter الزر a مؤمّن تعليمات برمجية, it will wait, حظر, until the كائن هو released.

The مقطع مؤشر الترابط (البرمجة C# الدليل) discusses threading.

The lock كلمة أساسية calls Enter at the يبدأ of the حظر و Exit at the إنهاء of the حظر.

في عام, avoid locking تشغيل a public نوع, أو instances beyond your تعليمات برمجية's عنصر تحكم. The عام constructs lock (this), lock (typeof (MyType)), و lock ("myLock") violate this guideline:

  • lock (this) هو a problem if the مثيل can be accessed publicly.

  • lock (typeof (MyType)) هو a problem if MyType هو publicly accessible.

  • lock(“myLock”) هو a problem because أي غير ذلك تعليمات برمجية في the عملية using the same سلسلة, will يجعله مشتركًا the same قفل.

أفضل ممارسة هو إلى define a private كائن إلى قفل تشغيل, أو a private static كائن متغير إلى يحمي بيانات عام إلى الجميع instances.

مثال

يبين نموذج التالي بسيط استخدم من مؤشرات الترابط بدون تأمين في C#‎.

    //using System.Threading;

    class ThreadTest
    {
        public void RunMe()
        {
            Console.WriteLine("RunMe called");
        }

        static void Main()
        {
            ThreadTest b = new ThreadTest();
            Thread t = new Thread(b.RunMe);
            t.Start();
        }
    }
    // Output: RunMe called

يستخدم نموذج التالي عمليات جزئية و lock. طالما lockجملة هو تقديم حظر عبارة هو مقطع حرج و balanceلا يصبح رقم سالب.

    // 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();
            }
        }
    }

مواصفات لغة #C

لمزيد من المعلومات، راجع مواصفات لغة #C. مواصفات اللغة هي المصدر النهائي لبناء جملة C# واستخدامها.

راجع أيضًا:

المرجع

مؤشر الترابط (البرمجة C# الدليل)

الكلمات الأساسية لـ #C

الكلمات الأساسية للعبارات (مرجع #C)

MethodImplAttributes

Mutex

مؤشر الترابط تزامن (برمجة دليل C#)

المبادئ

دليل البرمجة لـ #C

أجهزة العرض

عمليات interlocked

AutoResetEvent

موارد أخرى

مرجع C#‎