C#lock(mylocker)不起作用

我有很多web服务调用(asychronous),在回调中,我将结果绘制到Excel。 我想同步绘图方法。 所以我使用以下内容,但是,从我在Visual Studio中跟踪,每次锁定(locker)成功,并且有许multithreading运行clearcommentIfany,plot。 我无法弄清楚为什么这不能按预期工作! 谢谢

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's 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's 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().GetEvent().Publish(ID); } } 

我怀疑你的问题是你的锁是实例成员而不是静态(类型级别)成员。

假设每个线程都有自己的包含类的实例,那么它也将拥有自己的锁定器实例 – 这不是你想要的。

请尝试此声明:

 private static readonly object locker = new object(); 

现在包含static关键字使得此对象实例存在于类型级别,即在类的所有实例中共享。

您必须使对象保持static

  private static readonly object locker = new object(); 

目前,该类的每个实例(以及每个线程)都有自己的锁定器实例。