title: Best practice to delay thread without impacting performance or preventing memory leak?
body: <p>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.</p>
  <p>To prevent the same job from running I am using distributed lock <a href="https://github.com/madelson/DistributedLock" rel="nofollow noreferrer">library</a> where one pod will be acquiring the lock and the remaining pod will be waiting until another pod leaves the lock.</p>
  <pre><code>while (true) {
  
    var killingToken = new CancellationTokenSource();
    try {
      Console.WriteLine(&quot;Trying to acquire the lock&quot;);
      using
      var handle = await @lock.TryAcquireAsync();
      if (handle != null) {
  
        handle.HandleLostToken.Register(async () =&gt; {
          await StopAsync(cancellationToken);
          killingToken.Cancel();
        });
  
        jobMetadatas?.ForEach(jobMetadata =&gt; {
          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($&quot;{DateTime.Now} not acquired lock&quot;);
      }
    } catch (Exception e) {
      killingToken.Cancel();
    }
  }
  </code></pre>
  <p>So in the above code, the variable &quot;handle&quot; will be having the lock until the variable handle dispose.</p>
  <pre><code>using var handle = await @lock.TryAcquireAsync();
  </code></pre>
  <p>To prevent the dispose of handle variable. I am delaying the thread with the following statement.</p>
  <pre><code>Task.Delay(Timeout.InfiniteTimeSpan, killingToken.Token).GetAwaiter().GetResult();
  </code></pre>
  <p>Is there any better way in handling the following case? Please suggest me.</p>
  <p>Thanks in advance.</p>