在方法中锁定任务,该方法在 class 的不同实例上调用

Locking tasks in a method, which is called on different instances of a class

我有以下方法,由我的 ReportGenerator class 的不同实例调用。 ReportGenerator class 启动单个任务,该任务使用包含此方法的 class 的接口访问以下方法。

 public IRapportBestilling GetNextReportOrderAndLock(DateTime nextTimeoutValue, string correlationId, Func<EstimatedReportSize?, int, bool> getPermission, int taskId)
    {
        this.ValidateReportOrderQueueTimeout(nextTimeoutValue, correlationId);
        IRapportBestillingKoe reportOrderQueue;         
        try
        {            
            using (var scope = new QueryEngineSessionScope())
            {
 --> Lock here   bool allowLargeReports = getPermission.Invoke(EstimatedReportSize.RequestForLarge, taskId); 
                reportOrderQueue = this.rapportBestillingKoeRepository.GetNextReportOrderQueueItem(scope, correlationId, allowLargeReports, taskId);                    

                reportOrderQueue.Laast = true;
                reportOrderQueue.Timeout = nextTimeoutValue;
                this.rapportBestillingKoeRepository.Save(reportOrderQueue, scope, correlationId);
                scope.Complete(); 

 --> Release lock getPermission.Invoke(reportOrderQueue.EstimeretRapportStoerelse, taskId);

                var rep = this.rapportBestillingRepository.GetDomainObjectById(reportOrderQueue.RapportBestillingId, scope, correlationId);

                rep.StorRapport = (reportOrderQueue.EstimeretRapportStoerelse == EstimatedReportSize.Large); 
                return rep;
            }
        }
    }

我只需要允许单个任务执行上面显示的方法中的代码块。我已经使用 Interlocked 和 Monitor class 来处理这个问题,但这不起作用,因为在我的 class 的不同实例上调用了此方法。有没有办法处理这个问题?

您可以使用 Monitor 来做到这一点,只需锁定一个静态对象,以便它在所有实例之间共享。

private static object _lock = new object();

public IRapportBestilling GetNextReportOrderAndLock(...)
{
    ...
    using (var scope = new QueryEngineSessionScope())
    {
        lock(_lock)
        {
            ...
        }
    }
}