c# – 这是使用静态队列线程安全吗?
msdn文档指出静态通用队列是线程安全的.这是否意味着以下代码是线程安全的?换句话说,当一个线程启动一个int和另一个线程时,是否有同时出现一个int的问题?我必须锁定线程安全的入队和出队操作吗?
class Test { public static Queue<int> queue = new Queue<int>(10000); Thread putIntThread; Thread takeIntThread; public Test() { for(int i = 0; i < 5000; ++i) { queue.Enqueue(0); } putIntThread = new Thread(this.PutInt); takeIntThread = new Thread(this.TakeInt); putIntThread.Start(); takeIntThread.Start(); } void PutInt() { while(true) { if(queue.Count < 10000) {//no need to lock here as only itself can change this condition queue.Enqueue(0); } } } void TakeInt() { while(true) { if(queue.Count > 0) {//no need to lock here as only itself can change this condition queue.Dequeue(); } } } } 编辑:我必须使用.NET 3.5 解决方法
这绝对不是线程安全的.从
Queue<T> 的文件.
重读你的问题,你似乎对这个短语“这种类型的静态成员”感到困惑 – 这不是说“静态队列”,因为没有这样的事情.一个对象不是静态的 – 一个成员是.当谈到静态成员时,它谈论的是Encoding.GetEncoding(Queue< T>实际上没有任何静态成员).实例成员是Enqueue和Dequeue – 与类型实例相关的成员,而不是类型本身. 因此,您需要为每个操作使用锁定,或者如果您使用的是.NET 4,请使用 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |