Syncronization Exception
Posted
by Kurru
on Stack Overflow
See other posts from Stack Overflow
or by Kurru
Published on 2010-03-29T14:38:13Z
Indexed on
2010/03/30
21:23 UTC
Read the original article
Hit count: 468
Hi
I have two threads, one thread processes a queue and the other thread adds stuff into the queue.
- I want to put the queue processing thread to sleep when its finished processing the queue
- I want to have the 2nd thread tell it to wake up when it has added an item to the queue
However these functions call System.Threading.SynchronizationLockException: Object synchronization method was called from an unsynchronized block of code
on the Monitor.PulseAll(waiting);
call, because I havent syncronized the function with the waiting object. [which I dont want to do, i want to be able to process while adding items to the queue]. How can I achieve this?
Queue<object> items = new Queue<object>();
object waiting = new object();
1st Thread
public void ProcessQueue()
{
while (true)
{
if (items.Count == 0)
Monitor.Wait(waiting);
object real = null;
lock(items) {
object item = items.Dequeue();
real = item;
}
if(real == null)
continue;
.. bla bla bla
}
}
2nd Thread involves
public void AddItem(object o)
{
... bla bla bla
lock(items)
{
items.Enqueue(o);
}
Monitor.PulseAll(waiting);
}
© Stack Overflow or respective owner