-
use of lock object
I am writing a dll which runs several threads reading from a Queue, the calling program calls EnqueueTask with a data object. If I use lock around the queue object nothing goes in the queue, if I comment the lock than it works well (but causes a problem with the threads)
Please help
Code:
public class messagesQueue :IDisposable
{
EventWaitHandle waitHandle = new AutoResetEvent (false);
Thread _workerThread;
object locker = new object();
Queue<reportData> _messageQueue;// = new Queue<reportData>();
/// <summary>
/// Constructor
/// </summary>
public messagesQueue()
{
_messageQueue = new Queue<reportData>();
}
/// <summary>
/// Add record to the queue
/// </summary>
/// <param name="reportDataObj"></param>
public void EnqueueTask(reportData reportDataObj)
{
lock (locker)
{
_messageQueue.Enqueue(reportDataObj);
}
waitHandle.Set();
}
-
Re: use of lock object
There's nothing wrong with the attached code. The locking is fine. It definitely wouldn't cause the issue you're describing.
If there's a bug, it's in the rest of the code that you didn't paste.
-
Re: use of lock object
Keep in mind that you need to lock around any code that accesses the queue.
You've shown locking code for Enqueue operations, just make sure there are locks for any other queue operations.
-
Re: use of lock object
Just nothing goes and the program continue, or it freeze? And are you sure, that nothing goes into the queue? Maybe something (other thread) is retrieving it from the queue before you spot it's presense.
-
Re: use of lock object
Nothing happens with the queue, no data is going in. what I found out is that it works if I do Rebuild solution but if I just press F5 than nothing goes on.
-
Re: use of lock object
After rebuilding it works, but how do you start the application then??
-
Re: use of lock object
If it's randomly working/failing it's quite possible you have a race condition in your code, so post up the rest of the code. Running with the debugger could easily trigger the race as compared to running without. What you're explaining makes no sense at the moment, more info is needed ;)
-
Re: use of lock object
After rebuilding I start my application with F5, I will post more code later today.