Search code examples
c#loopstimerwait

How to wait in loop without blocking UI in C#


I'm working on a project and I need some help. Here's a code snippet:

private void MassInvoiceExecuted()
{
    foreach (Invoice invoice in Invoices)
    {
        DoStuff(invoice);
        //I'd like to wait 8 seconds here before the next iteration
    }

    RefreshExecuted();
}

How can this be done easily? What I've tried is:

private async void MassInvoiceExecuted()
{
    foreach (Invoice invoice in Invoices)
    {
        DoStuff(invoice);
        await Task.Delay(8000);
    }

    RefreshExecuted();
}

And although it did wait 8 seconds without freezing the UI it also waited for about 30 seconds right before RefreshExecuted(); I'm obviously not familiar with async await but it seemed like a good idea.

Anyway, I need to wait 8 seconds after each iteration without blocking the UI because I have to be able to abort the loop via button click. I've considered timers. Setting up the interval to 8000 and creating a tick method containing what exactly? I can't put everything that's in MassInvoiceExecuted inside the tick method because that wouldn't be right.

Any help would be much appreciated. Thanks!


Solution

  • For what i understand of your answer maybe you want

    private async void MassInvoiceExecuted()
    {     
        foreach (Invoice invoice in Invoices)
        {
            DoStuff(invoice);
            RefreshExecuted();
            await Task.Delay(8000);
        }
    }
    

    But really don't know if you have any reason to update UI only at the end of all processing.