Home > database >  How to do a while loop on an async retrieved list?
How to do a while loop on an async retrieved list?

Time:09-07

So I have this Task:

public async Task ProcessNewMessages()
{
    while (true)
    {
        await _exceptionHandler.WithExceptionHandling(async () =>
        {
            List<Message> newUncompletedNewMessages = await _newUncompletedMessagesJob.Execute();
            // Do stuff
        }
        Thread.Sleep(30000);
    }
}

The Execute returns a list of 10 messages and I want to add a while loop in the while true that runs the whole code again as long as the Execute returns me a full list of 10 items, that runs straight after the items are done rather than waiting 30 seconds every time.

The 30 seconds will be in place to keep checking if there are new messages and is ireelevant to the Task of handling them.

So to rephrase my question: How do I rerun code based on the list returned by Execute() having 10 messages?

CodePudding user response:

public async Task ProcessNewMessages()
{
    while (true)
    {
        IEnumerable<MessageToSend> uncompletedNewMessages = new List<MessageToSend>();
        do
        {
            await _exceptionHandler.WithExceptionHandling(async () =>
            {
                uncompletedNewMessages = await _newUncompletedMessagesJob.Execute();
                // DoStuff
            });
        } while (uncompletedNewMessages.Count() == 10)
        await Task.Delay(30000);
    }
}   

I have an answer.

I read people not liking the Thread.Sleep, but this is a webjob running continuously to check for new messages. Now this doesn't need to run every second, because there might not be new message every second, but they can keep on coming in throughout the day. Let me know your suggestions how to do that differently.

Edit: Thanks for the explanation Jeroen

  • Related