© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•2y ago•
7 replies
UltraWelfare

✅ Waiting on a task more efficiently

I've made this class for my application that needs to process some things in the background using a queue:

public class IcsBackgroundQueue
{
    private ConcurrentQueue<IcsCashDesk> _jobQueue = new();

    private OrdersDB _ordersDb = new(Types.Order.sell);
    private Task _processingTask;
    private CancellationTokenSource _cts = new();

    public IcsBackgroundWorker()
    {
        _processingTask = Task.Run(ProcessJobs, _cts.Token);
    }

    // ... stop function, enqueue function etc

    private async Task ProcessJobs()
    {
        while (!_cts.IsCancellationRequested)
        {
            try
            {
                if (_jobQueue.IsEmpty)
                {
                    await Task.Delay(1000, _cts.Token);
                    continue;
                }
                
                _jobQueue.TryDequeue(out var cashDesk);
                if (cashDesk == null) continue;
                await cashDesk.CompleteWaitAsync();
            }
            catch (OperationCanceledException)
            {
            }
        }
    }
}
public class IcsBackgroundQueue
{
    private ConcurrentQueue<IcsCashDesk> _jobQueue = new();

    private OrdersDB _ordersDb = new(Types.Order.sell);
    private Task _processingTask;
    private CancellationTokenSource _cts = new();

    public IcsBackgroundWorker()
    {
        _processingTask = Task.Run(ProcessJobs, _cts.Token);
    }

    // ... stop function, enqueue function etc

    private async Task ProcessJobs()
    {
        while (!_cts.IsCancellationRequested)
        {
            try
            {
                if (_jobQueue.IsEmpty)
                {
                    await Task.Delay(1000, _cts.Token);
                    continue;
                }
                
                _jobQueue.TryDequeue(out var cashDesk);
                if (cashDesk == null) continue;
                await cashDesk.CompleteWaitAsync();
            }
            catch (OperationCanceledException)
            {
            }
        }
    }
}


Is there anything to do to better optimize the while loop when no jobs are in the queue? I've done a simple 1s delay but I'd bet there's a better way of doing it..?
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

Any way to declare these variables more efficiently?
C#CC# / help
4y ago
❔ Task stuck on WaitingforActivation
C#CC# / help
4y ago
❔ Cancel task on nested exception
C#CC# / help
3y ago
❔ Clarification on Async and Task.Run
C#CC# / help
3y ago