我有以下方法,由ReportGenerator类的不同实例调用。 ReportGenerator类启动单个任务,该任务使用包含此方法的类的接口访问以下方法。
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类来处理这个问题,但这不起作用,因为在我的类的不同实例上调用了这个方法。有办法解决这个问题吗?
答案 0 :(得分:2)
您可以使用Monitor
执行此操作,只需锁定静态对象,以便在所有实例之间共享。
private static object _lock = new object();
public IRapportBestilling GetNextReportOrderAndLock(...)
{
...
using (var scope = new QueryEngineSessionScope())
{
lock(_lock)
{
...
}
}
}