I am trying to create an async method in Blazor that allows me to run computationally-heavy code asynchronously and then update a component when done, all while keeping the page responsive. The difference between this question and other questions about async in Blazor, is that I am creating a method that takes a long time versus using something like HttpClient's download methods.
The components:
page.blazor
@inject ClassA classA
<button class="btn btn-primary" @onclick="@doWork">Do Work</button>
<Text>@log</Text>
@code {
async Task doWork()
{
log = await classA.doWork();
}
}
C# classes
public class ClassA
{
public async Task<string> doWork()
{
ClassB classB = new ClassB();
var result = await classB.Execute();
return result;
}
}
public class ClassB
{
// This method is meant to take a long time and execute asynchronously
public async Task<string> Execute()
{
string k = "";
for (int i = 0; i < 10000000; i ++)
{
k = i.ToString();
}
return k;
}
}
Note: If I change the code in page.blazor to
@code {
async Task doWork()
{
await Task.Delay(10000);
log = "Done";
}
}
it works properly.