Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# await on a List<T> Count

I am upgrading some legacy WinForms code and I am trying to figure out what the "right way" as of .NET 4.6.1 to refactor the following.

The current code is doing a tight while(true) loop while checking a bool property. This property puts a lock() on a generic List<T> and then returns true if it has no items (list.Count == 0).

The loop has the dreaded Application.DoEvents() in it to make sure the message pump continues processing, otherwise it would lock up the application.

Clearly, this needs to go.

My confusion is how to start a basic refactoring where it still can check the queue length, while executing on a thread and not blowing out the CPU for no reason. A delay between checks here is fine, even a "long" one like 100ms+.

I was going to go with an approach that makes the method async and lets a Task run to do the check:

await Task.Run(() => KeepCheckingTheQueue());

Of course, this keeps me in the situation of the method needing to ... loop to check the state of the queue.

Between the waiting, awaiting, and various other methods that can be used to move this stuff to the thread pool ... any suggestion on how best to handle this?

like image 208
Patrick Avatar asked Nov 30 '25 04:11

Patrick


1 Answers

What I need is how to best "poll' a boolean member (or property) while freeing the UI, without the DoEvents().

The answer you're asking for:

private async Task WaitUntilAsync(Func<bool> func)
{
  while (!func())
    await Task.Delay(100);
}

await WaitUntilAsync(() => list.Count == 0);

However, polling like this is a really poor approach. If you can describe the actual problem your code is solving, then you can get better solutions.

For example, if the list represents some queue of work, and your code is wanting to asynchronously wait until it's done, then this can be better coded using an explicit signal (e.g., TaskCompletionSource<T>) or a true producer/consumer queue (e.g., TPL Dataflow).

like image 170
Stephen Cleary Avatar answered Dec 02 '25 18:12

Stephen Cleary