學習心得:關於C#中Queue的安全執行緒問題

來源:互聯網
上載者:User
 

        若要保證 Queue 的安全執行緒,必須通過此封裝執行所有操作。

通過集合枚舉在本質上不是一個安全執行緒的過程。甚至在對集合進行同步處理時,其他線程仍可以修改該集合,這會導致枚舉數引發異常。若要在枚舉過程中保證安全執行緒,可以在整個枚舉過程中鎖定集合,或者捕捉由於其他線程進行的更改而引發的異常。

下列樣本說明如何同步 Queue、如何確定 Queue 是否同步以及如何使用同步的 Queue。
[C#]
using System;
using System.Collections;
public class SamplesQueue  {

   public static void Main()  {

      // Creates and initializes a new Queue.
      Queue myQ = new Queue();
      myQ.Enqueue( "The" );
      myQ.Enqueue( "quick" );
      myQ.Enqueue( "brown" );
      myQ.Enqueue( "fox" );

      // Creates a synchronized wrapper around the Queue.
      Queue mySyncdQ = Queue.Synchronized( myQ );

      // Displays the sychronization status of both Queues.
      Console.WriteLine( "myQ is {0}.", myQ.IsSynchronized ? "synchronized" : "not synchronized" );
      Console.WriteLine( "mySyncdQ is {0}.", mySyncdQ.IsSynchronized ? "synchronized" : "not synchronized" );
   }
}
/*
This code produces the following output.

myQ is not synchronized.
mySyncdQ is synchronized.
*/

          通過對比運行結果,可以明顯的看出通過Queue.Synchronized方法封裝的Queue被同步,沒有封裝的則沒有被同步。可以在執行個體化處這樣聲明,

// Creates a synchronized wrapper around the Queue.
      Queue mySyncdQ = Queue.Synchronized( new Queue());

這樣在多線程環境下可以使用Queue的同步對象鎖,來防止多線程同時對Queue進行寫操作。如果想讓其它線程不能訪問Queue對象,則可以使用lock(queue),來達到這個目的。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.