C# 線程手冊 第三章 使用線程 Monitor.TryEnter()


Monitor 類的TryEnter() 方法在嘗試獲取一個對象上的顯式鎖方面和 Enter() 方法類似。然而,它不像Enter()方法那樣會阻塞執行。如果線程成功進入關鍵區域那么TryEnter()方法會返回true.

TryEnter()方法的三個重載方法中的兩個以一個timeout類型值作為參數,表示按照指定時間等待鎖。我們來看一個關於如何使用TryEnter()方法的例子,MonitorTryEnter.cs:

/*************************************
/* Copyright (c) 2012 Daniel Dong
 * 
 * Author:oDaniel Dong
 * Blog:o  www.cnblogs.com/danielWise
 * Email:o guofoo@163.com
 * 
 */

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace MonitorTryEnter
{
    public class TryEnter
    {
        public TryEnter()
        {
        }

        public void CriticalSection()
        {
            bool b = Monitor.TryEnter(this, 1000);
            Console.WriteLine("Thread "
                + Thread.CurrentThread.GetHashCode()
                + " TryEnter Value " + b);

            if (b)
            {
                for (int i = 1; i <= 3; i++)
                {
                    Thread.Sleep(1000);
                    Console.WriteLine(i + " "
                        + Thread.CurrentThread.GetHashCode() + " ");
                }
            }
            if (b)
            {
                Monitor.Exit(this);
            }
        }

        public static void Main()
        {
            TryEnter a = new TryEnter();
            Thread t1 = new Thread(new ThreadStart(a.CriticalSection));
            Thread t2 = new Thread(new ThreadStart(a.CriticalSection));
            t1.Start();
            t2.Start();

            Console.ReadLine();
        }
    }
}

一個可能的輸出結果如下:

Capture

當發生資源爭奪而你又不像讓線程睡眠一段不可預期的時間時TryEnter()方法很有用。向ISP撥號的例子很好的解釋這個。假設有兩個程序A和B,它們都想使用同一個調制解調器向ISP撥號。而一旦連接建立那么只會有一個網絡連接,我們不知道已有的應用程序將會連接多長時間。假設程序A首先向ISP撥號,然后程序B也向ISP撥號;毫無疑問程序B將會一直等待,因為我們不知道程序A將連接多久。在這種情況下,程序B可能使用TryEnter()來確定調制解調器是否已經被另外一個應用程序鎖定(本例中是程序A),而不是使用Enter()方法導致一直等待。

 

lock 關鍵字

lock 關鍵字可以作為Monitor類的一個替代。下面兩個代碼塊是等效的:

Monitor.Enter(this);
//...
Monitor.Exit(this);

lock (this)
{
    //...
}

下面的例子, Locking.cs, 使用lock 關鍵字而不是Monitor方法:

/*************************************
/* copyright (c) 2012 daniel dong
 * 
 * author:daniel dong
 * blog:  www.cnblogs.com/danielwise
 * email: guofoo@163.com
 * 
 */

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace Lock
{
    class LockWord
    {
        private int result = 0;

        public void CriticalSection()
        {
            lock (this)
            {
                //Enter the Critical Section
                Console.WriteLine("Entered Thread "
                    + Thread.CurrentThread.GetHashCode());

                for (int i = 1; i <= 5; i++)
                {
                    Console.WriteLine("Result = " + result++
                        + " ThreadID "
                        + Thread.CurrentThread.GetHashCode());
                    Thread.Sleep(1000);
                }
                Console.WriteLine("Exiting Thread "
                    + Thread.CurrentThread.GetHashCode());
            }
        }

        public static void Main(string[] args)
        {
            LockWord e = new LockWord();

            Thread t1 = new Thread(new ThreadStart(e.CriticalSection));
            t1.Start();

            Thread t2 = new Thread(new ThreadStart(e.CriticalSection));
            t2.Start();

            //Wait till the user enters something
            Console.ReadLine();
        }
    }
}

Locking.cs 的輸出與MonitorEnterExit(需要提供一個參數)一樣:

Lock

 

下一篇將介紹ReaderWriterLock 類…


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM