Skip to content

Commit

Permalink
Protect DI scheduler initialization from concurrent initialization (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
lahma committed Aug 1, 2021
1 parent f376d69 commit 6e989ec
Showing 1 changed file with 19 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ internal class ServiceCollectionSchedulerFactory : StdSchedulerFactory
private readonly IOptions<QuartzOptions> options;
private readonly ContainerConfigurationProcessor processor;
private bool initialized;
private readonly SemaphoreSlim initializationLock = new SemaphoreSlim(1, 1);

public ServiceCollectionSchedulerFactory(
IServiceProvider serviceProvider,
Expand All @@ -44,6 +45,24 @@ public override async Task<IScheduler> GetScheduler(CancellationToken cancellati
return scheduler;
}

await initializationLock.WaitAsync(cancellationToken);
try
{
if (!initialized)
{
await InitializeScheduler(scheduler, cancellationToken);
initialized = true;
}
}
finally
{
initializationLock.Release();
}
return scheduler;
}

private async Task InitializeScheduler(IScheduler scheduler, CancellationToken cancellationToken)
{
foreach (var listener in serviceProvider.GetServices<ISchedulerListener>())
{
scheduler.ListenerManager.AddSchedulerListener(listener);
Expand All @@ -70,8 +89,6 @@ public override async Task<IScheduler> GetScheduler(CancellationToken cancellati
}

await processor.ScheduleJobs(scheduler, cancellationToken);
initialized = true;
return scheduler;
}

protected override T InstantiateType<T>(Type? implementationType)
Expand Down

0 comments on commit 6e989ec

Please sign in to comment.