Threading problem with some old code

I have a project recently upgraded from .net 1.1 to .net 4.0. We get an error from the user-defined "ThreadPool" class (yes, someone felt the need to write their own), and now I'm wondering what it could be.

The error is issued from the following code:

private void Submit(WorkItem work) { this.AdjustPoolSize(); lock (this.workQueue.SyncRoot) { //Monitor.Enter(workQueue); this.workQueue.Enqueue(work); Monitor.Pulse(this.workQueue.SyncRoot); //Monitor.Exit(workQueue); } } 

Commented code is how the code was passed to me. Unfortunately, I don’t know much about this project and only here to fix this problem. We see an error:

 System.Threading.SynchronizationLockException was unhandled by user code Message=Object synchronization method was called from an unsynchronized block of code. Source=mscorlib StackTrace: at System.Threading.Monitor.ObjPulse(Object obj) at System.Threading.Monitor.Pulse(Object obj) at CustomThreadPoolObject.Submit(WorkItem work) in D:\...\Threading.cs:line 1438 at CustomThreadPoolObject.Submit(WaitCallback callback, Object state) in D:\...\Threading.cs:line 1349 at SomeGroupProcessFunctionality.Submit(PooledThread thread, TaskInfo task, String appServer, Hashtable batchHandleTable) in D:\...\ProcessGroup.cs:line 143 at System.Runtime.Remoting.Messaging.Message.Dispatch(Object target, Boolean fExecuteInContext) at System.Runtime.Remoting.Messaging.StackBuilderSink.SyncProcessMessage(IMessage msg, Int32 methodPtr, Boolean fExecuteInContext) InnerException: 

In appearance, something works as β€œaffordable” when it really is not. I tried to do this and found http://bbellomo.blogspot.com/2007/03/object-synchronization-method-was.html , but this did not help me since I did not quite understand how its problem and resolution.

Hope someone can give me some advice.

Thanks!

+4
source share
1 answer

Because you are using your own thread pool mechanism. Then the exception is probably due to the fact that the thread changed after lock and before calling Monitor.Pulse . according to msdn, this exception will be thrown on Pulse if:

The calling thread has no lock on the specified object.

Edit: Or you are blocked in another thread after the first lock ", perhaps in the producer thread that disables WorkItem and starts them in the pool, you call lock (this.workQueue.SyncRoot) " in this thread until it reaches Monitor.Pulse(this.workQueue.SyncRoot); .

+1
source

All Articles