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

來源:互聯網
上載者:User

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

 

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

當發生資源爭奪而你又不像讓線程睡眠一段不可預期的時間時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(需要提供一個參數)一樣:

作者:DanielWise
出處:http://www.cnblogs.com/danielWise/

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.