2014-04-11 21 views
2

我想教自己關於C#中的線程,並且遇到了問題。可以說這是我的代碼:來自線程的C#訪問類成員

class MyClass 
{ 
    public Queue variable; 
    internal MyClass() 
    { 
     variable = new Queue<int>(); 
     variable.Enqueue(1); 
     Thread thread = new Thread(new ThreadStart(DoSomething)); 
     thread.IsBackground = true; 
     thread.Start(); 
    } 
    public void DoSomething() 
    { 
     int i = variable.Dequeue(); 
     MessageBox.Show(i); 
    } 
} 

執行時,我收到一個異常,說當我試圖出隊時隊列是空的。調試顯示隊列在線程的上下文中是空的,但不在較大的類中。我假設C#爲某些東西創建線程局部對象(但不是全部,如果我要創建一個int成員變量,我可以在線程中獲得它的值而沒有任何問題)我知道java確實是類似的東西,它是將成員變量聲明爲「volatile」或類似的東西。 C#有一個類似的構造,但我不認爲它是我正在尋找的(或者至少,我使用它,它並沒有幫助...)我將如何在C#中聲明一個成員變量,以便任何線程創建的類也可以訪問它嗎? (我也很想更好地理解這個東西,所以鏈接到相關的材料將不勝感激)

+0

您需要使用[Synchronized](http://msdn.microsoft.com/en-us/library/system.collections.queue.synchronized.aspx)方法。 – Icemanind

+0

你的假設是錯誤的。 –

+0

你的代碼工作正常。只需聲明int類型的隊列即可。 –

回答

1
class MyClass { 
    public Queue variable; 
    internal MyClass() { 
     variable = new Queue(); 
     variable.Enqueue(1); 
     Thread thread = new Thread(new ThreadStart(DoSomething)); 
     thread.IsBackground = true; 
     thread.Start(); 
    } 
    public void DoSomething() { 
     int i = (int)(variable.Dequeue()); //cast required here 
     //MessageBox may not play nice from non-ui thread 
     Console.WriteLine(i); 
    } 
} 

工作正常,只有最小的編輯。隊列在線程中可見。目前還不清楚你是如何得出不同的結論的。

您可能會考慮使用通用的Queue<int>avoid the boxing/unboxing associated with storing value types in non-generic collections

更好的是,通過使用ConcurrentQueue<T>,您可以避免大量嘈雜的線程同步,因爲您在線程之間共享此隊列。

0

我認爲你應該改變這兩條線,它應該工作。

public Queue<int> variable; 

MessageBox.Show(i.ToString());