相互排斥
我有一个应用程序,它使用来自不同线程的集合(在本例中是队列)。一个对象在一个线程中排队,而另一个对象在另一个线程中出队。
当重新定义集合计数器时,这些操作可能会同时发生,这将在异常中解决,例如参数超出范围异常。
我正在寻找一种“好看的”以及正确的理由来相互排除这些行为。
我所说的“好看”是指我不想创建自己的包含锁(对象)机制的集合派生
我不想使用我的头脑风暴想法,这相当“丑”
enqueueOk = false;
while (!enqueueOk)
{
try
{
Qsockets.Enqueue(currentSoc);
enqueueOk = true;
}
catch { }
}
我当然认为使用锁或互斥体,但只有当我将这些操作包装在一个称为“程序”的过程中时才会出现这种情况从每个线程,并决定是入队还是出队,这也将是又长又“丑陋”的
编辑:
因为似乎没有人看到我的答案,
我只是在集合本身上使用了锁定机制
lock(Qsockets)
{
Qsockets.Enqueue(currentSoc);
}
I have an application which uses a collection, in this case a queue, from different threads. An object gets enqueued in one thread while another gets dequeued in a different thread.
These actions might occur simultaneously which would resolve in an exception such as argument out of range exception, when the collections counter is being redefined.
I'm looking for a "good looking" and right why to exclude these actions from one another.
what I mean by "good looking" is that I don't want to create my own collection derived from this one which includes a lock(object) mechanism
I don't want to use the brain storming idea I had, which is pretty "ugly"
enqueueOk = false;
while (!enqueueOk)
{
try
{
Qsockets.Enqueue(currentSoc);
enqueueOk = true;
}
catch { }
}
I thought of course using the a lock or a mutex but that would be the case only if I wrap these actions in a procedure which would be called from each thread, and decide either to enqueue or dequeue which would also be long and "ugly"
edit:
because no one seems to see my answer down below
I just used the lock mechanism on the collection itself
lock(Qsockets)
{
Qsockets.Enqueue(currentSoc);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
可以使用 TPL 吗? ConcurrentQueue 自动处理并发活动。
http://msdn.microsoft.com/en-us/library/dd267265.aspx
Can you use the TPL? ConcurrentQueue automatically handles concurrent activity.
http://msdn.microsoft.com/en-us/library/dd267265.aspx
您始终拥有 .Net 4 中的 ConcurrentQueue 类,如果 .Net 4是一个选项。它在类内部实现了锁定。
You always have the ConcurrentQueue Class from .Net 4, if .Net 4 is an option. Which implements locking inside the class.
您可以使用并发队列或同步队列。
You can use Concurrent Queue or Synchronise the queue.
使用 ConcurrentQueue(4.0 中提供)。请参阅 http://msdn.microsoft.com/en-us/library/dd267265。 ASPX
Use a ConcurrentQueue (available in 4.0). See http://msdn.microsoft.com/en-us/library/dd267265.aspx
看起来像一个经典的生产者-消费者场景。您检查过这个漂亮的示例吗?
Seems like a classic Producer-Consumer scenario. Have you check this nice example?
lock 语句是处理这些事情的首选方法,.NET Framework 中内置的“线程安全”集合依赖于它们。去做就对了。
The lock statement is the go-to way to handle these things, and "thread-safe" collections built into the .NET Framework rely on them. Just do it.
我刚刚从一篇以字节为单位的帖子中得出结论,
我可以锁定实际的集合
锁(Qsockets)
{
Qsockets.Enqueue(currentSoc);
}
i just concluded from a post in bytes ,
that i could just lock the actual collection
lock(Qsockets)
{
Qsockets.Enqueue(currentSoc);
}