Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delay a task in Blazor without blocking the UI

I created a .razor Notification Component in Blazor, and I'm trying to autoclose the notification div after xx seconds.

So far it works with this Method

 private async Task CloseToast(Guid Id, bool autoclose = false)
{
    if (autoclose)
    {
        await Task.Delay(TimeSpan.FromSeconds(5));
    }

   //Code to remove the notification from list
    StateHasChanged();
}

The problem is that for 5 seconds the UI data binding is stuck, any one way or two way binding update to variables (text fields etc..) is on hold until the Notification is closed and the Task resumes.

How can I launch a method or code block after xx seconds without blocking the main UI task in Blazor?

like image 762
Francesco Cristallo Avatar asked Oct 08 '19 23:10

Francesco Cristallo


1 Answers

A component with a timer that counts back


<h3>@Time</h3>

@code {
    [Parameter] public int Time { get; set; } = 5;

    public async void StartTimerAsync()
    {
        while (Time > 0)
        {
            Time--;
            StateHasChanged();
            await Task.Delay(1000);
        }
    }

    protected override void OnInitialized()
        => StartTimerAsync();
}

Usage:

<Component />
<Component Time="7"/>

Tested on client side Blazor. Should behave the same way in server-side Blazor. Hope this helps

like image 95
Zsolt Bendes Avatar answered Oct 19 '22 11:10

Zsolt Bendes