C#从线程访问类成员

时间:2014-04-11 20:46:44

标签: c# multithreading

我试图在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会做类似的事情,并且周围的方式它是将成员变量声明为&#34; volatile&#34;或类似的东西。 C#有一个类似的结构,但我不会想到它正在寻找的东西(或者至少,我使用它并且它没有帮助......)我如何声明一个成员变量在C#中,类创建的任何线程也可以访问它? (我也非常想更好地理解这些东西,所以非常感谢链接到相关材料)

2 个答案:

答案 0 :(得分: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>来避免一大堆嘈杂的线程同步,看到你在线程之间共享这个队列。

答案 1 :(得分:0)

我认为你应该改变这两行,它应该有用。

public Queue<int> variable;

MessageBox.Show(i.ToString());
相关问题