1

Consider the following code that loops until a precondition is satisfied. The call to CheckPrecondition() is not doing any resource-intensive work, it is simply checking a boolean flag which is set to true on a separate thread.

public async Task LoopUntilPreconditionIsSatisfied()
{
  bool preconditionIsSatisfied = false;

  while (!preconditionIsSatisfied)
  {
    var preconditionIsSatisfied = CheckPrecondition();

    // Is there a performance benefit to delaying this task?
    // How long should the delay be? Is it pointless if it's too short?
    await Task.Delay(10);
  }
}

Does adding await Task.Delay() meaningfully improve performance by releasing the thread to do other work?

Is there a recommended delay time? I want it to be long enough to actually be useful while short enough to react quickly to the precondition being satisfied. Obviously I could make it configurable but I would at least like to have a sensible default.

Alasdair Stark
  • 1,227
  • 11
  • 32
  • 4
    Maybe you can use a more established synchronization primitive instead of a loop around a boolean flag? https://learn.microsoft.com/en-us/dotnet/standard/threading/overview-of-synchronization-primitives – Oliver Aug 30 '23 at 09:07
  • 1
    If you own the context of `CheckPrecondition` you can convert it to an event-driven design. When the conditions are met you fire an event and in the event handler, you run your logic. – Eldar Aug 30 '23 at 09:14
  • 4
    If you're already in the world of tasks, the obvious is for whatever is setting that precondition flag to have a `TaskCompletionSource` instead and hand this code the corresponding `Task` to wait on. – Damien_The_Unbeliever Aug 30 '23 at 09:15
  • @Eldar what if there are several preconditions that have to be met? – Alasdair Stark Aug 30 '23 at 09:26
  • Depending on the usecase you might want to go a bit hardcore and consider using [`SpinWait`](https://learn.microsoft.com/en-us/dotnet/api/system.threading.spinwait?view=net-7.0) but in general I would argue refactoring to using signaling approach or the `Task` one would be in general a better option. – Guru Stron Aug 30 '23 at 09:28
  • 1
    Well, there is an `if` for that. As we don't know what you are actually trying to do or what the `CheckPrecondition` method is doing. – Eldar Aug 30 '23 at 09:29
  • How about `System.Threading.SpinWait.SpinUntil(CheckPrecondition);`? – Peter Csala Aug 30 '23 at 09:29
  • @AlasdairStark It depends on your exact scenario, but in general in the case of multiple preconditions, use `TaskCompletionSource`s to convert them into Task-based methods, and then use `Task.WhenAll` to await the completion of all of them. – John Aug 30 '23 at 09:29

0 Answers0