Blazor Live Search - A second operation started on this context before a previous operation completed

84 Views Asked by At

I have developed a Live Search functionality in Blazor that filters Customers in a database like this:

Razor file:

    <input type="text" class="form-control" @bind="filter.SearchQuery" @bind:event="oninput" @bind:after="LoadCustomers" placeholder="Search"></div>

Code:

{
    customerList = await CustomerViewModelService.GetCustomers(filter);
}

However, when quickly entering text in the search input, the GetCustomers method gets called multiple times before the first call is finished. So I get the following error: "System.InvalidOperationException: A second operation was started on this context instance before a previous operation completed"

I fixed this by blocking the second call until the first one is finished like this:

{
    if (!loading)
    {
        loading = true;
        customerList = await CustomerViewModelService.GetCustomers(filter);
        loading = false;
    }
}

But I am sure there is a better way to tackle this issue. Any suggestions?

1

There are 1 best solutions below

1
MrC aka Shaun Curtis On BEST ANSWER

This looks like an autocomplete control.

You have two problems:

Problem 1

Your data retrieval is slower than typing speed. To solve this you need to use a debouncing technique. The simplest, but often least satisfactory, is a backoff timer. Search "Blazor Debouncer" to find some examples.

If you want something a little more sophisticated check out these two articles on CodeProject. One by Jeremy Likeness and the other by me.

https://www.codeproject.com/Articles/5308567/An-Easier-Blazor-Debounce

https://www.codeproject.com/Articles/5351256/Building-a-Blazor-Autocomplete-Control

Problem 2

A second operation was started on this context instance before a previous operation completed

Suggests you are using a single DBContext for all your operations. Not good practice in Blazor.

See this MS Learn article which explains how to use the DbContextFactory.