Best practice to delay thread without impacting performance or preventing memory leak?

Viewed 42

In my application, Currently running the background tasks using the quartz.net library in the .net core. We will be deploying in Kubernetes and at least 2 pods will be running.

To prevent the same job from running I am using distributed lock library where one pod will be acquiring the lock and the remaining pod will be waiting until another pod leaves the lock.

while (true) {

  var killingToken = new CancellationTokenSource();
  try {
    Console.WriteLine("Trying to acquire the lock");
    using
    var handle = await @lock.TryAcquireAsync();
    if (handle != null) {

      handle.HandleLostToken.Register(async () => {
        await StopAsync(cancellationToken);
        killingToken.Cancel();
      });

      jobMetadatas?.ForEach(jobMetadata => {
        IJobDetail jobDetail = CreateJob(jobMetadata, handle);
        ITrigger trigger = CreateTrigger(jobMetadata);
        Scheduler.ScheduleJob(jobDetail, trigger, cancellationToken).GetAwaiter();
      });

      await Scheduler.Start(cancellationToken);

      Task.Delay(Timeout.InfiniteTimeSpan, killingToken.Token).GetAwaiter().GetResult();
    } else {

      Console.WriteLine($"{DateTime.Now} not acquired lock");
    }
  } catch (Exception e) {
    killingToken.Cancel();
  }
}

So in the above code, the variable "handle" will be having the lock until the variable handle dispose.

using var handle = await @lock.TryAcquireAsync();

To prevent the dispose of handle variable. I am delaying the thread with the following statement.

Task.Delay(Timeout.InfiniteTimeSpan, killingToken.Token).GetAwaiter().GetResult();

Is there any better way in handling the following case? Please suggest me.

Thanks in advance.

0 Answers
Related