Reputation: 1696
I have following method, which is called by different instances of my ReportGenerator class. The ReportGenerator class starts a single task, which accesses following method with an Interface to the class containing this method.
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;
}
}
}
I need to only allow a single task to be executing the code block in the method shown above. I have used Interlocked as well as Monitor class to handle this problem, but this is not working since this method is called on different instances of my class. Is there an approach to handle this problem ?.
Upvotes: 0
Views: 37
Reputation: 14896
You can do it with Monitor
, just lock on a static object so that it's shared between all instances.
private static object _lock = new object();
public IRapportBestilling GetNextReportOrderAndLock(...)
{
...
using (var scope = new QueryEngineSessionScope())
{
lock(_lock)
{
...
}
}
}
Upvotes: 2