C # lock (mylocker) not working

I have many web service calls (asynchronous), in the callback I will output the result in Excel. I want to synchronize the plotting method. Therefore, I use the following, however, when I exit Visual Studio, each time the locker is successful, and there are many threads that execute clearcommentIfany, plot. I cannot understand why this does not work as expected! thanks

private readonly object locker = new object(); void ProcessPlot() { lock (locker) { Debug.WriteLine("currentThreadID: " + Thread.CurrentThread.ManagedThreadId); //Helper.Dispatcher.Invoke(new AddClearCommentDelegate(ClearCommentIfAny)); ClearCommentIfAny(); if (Response.status != Status.COMPLETE) { ErrorMessage = ManipulateStatusMsg(Response); //Helper.Dispatcher.Invoke(new AddClearCommentDelegate(AddCommentToCell)); AddCommentToCell(); } else // COMPLETE { // TODO: Convert this into factory pattern Debug.WriteLine("ReportBuilder.Dispatcher address " + Helper.GetAddress(Helper.Dispatcher)); //Helper.Dispatcher.Invoke(new PlotDelegate(Plot), Response); Plot(Response); } } } public void DataRequestJobFinished(DataRequestResponse response) { try { if (Request.IsRequestCancelled) { Request.FormulaCell.Dispose(); return; } Response = response; //if (response.status != Status.COMPLETE) //{ // ErrorMessage = ManipulateStatusMsg(response); //} //else // COMPLETE //{ // // TODO: Convert this into factory pattern // PlotDelegate plotDelegate = Plot; // Debug.WriteLine("ReportBuilder.Dispatcher address " + Helper.GetAddress(Helper.Dispatcher)); // Helper.Dispatcher.Invoke(plotDelegate, response); // //Plot(response); //} var t = new Thread(ProcessPlot); t.Start(); //ProcessPlot(); } catch (Exception e) { ErrorMessage = e.Message; MIMICShared.Helper.LogError(e); } finally { //TODO: PutReportBuilderInQueue(this); ReadyForPlot = true; //Request.FormulaCell.Dispose(); move this after plot UnityContainer.Resolve<IEventAggregator>().GetEvent<DataRefreshEvent>().Publish(ID); } } 
+7
source share
2 answers

I suspect your problem is that your lock is an instance member and not static (level type).

Assuming each thread has its own instance of the containing class, then it will also have its own instance of your locker, which is not what you want.

Try this expression instead:

 private static readonly object locker = new object(); 

The inclusion of the static keyword now makes this instance of the object existing at the type level, that is, shared in all instances of your class.

+23
source

You will need to make a static object.

  private static readonly object locker = new object(); 

Currently, each instance of the class (and therefore each thread) has its own instance of the locker.

+3
source

All Articles