![](/img/trans.png)
[英]Q: How to form LINQ query to access nested attributes within class to display on Blazor WASM application
[英]How to display the execution of each parralel Task independenly on Blazor WASM?
有一個頁面,應該顯示兩個獨立異步操作的結果,例如 - REST 請求。
為了顯示第一個任務的結果(通過 Blazor 生命周期方法執行請求),我們需要等待兩個任務的執行,盡管來自第一個任務的數據是由服務獲取的。
如何在不等待第二個任務執行的情況下顯示第一個任務的結果?
只有在執行第二個任務后,第一個任務的結果才會顯示在頁面上。
服務
public class TaskService : ITaskService
{
public async Task<string> FirstTask()
{
const int timeOut = 500;
await Task.Delay(timeOut);
Console.WriteLine(timeOut);
return nameof(FirstTask) + timeOut;
}
public async Task<string> SecondTask()
{
const int timeOut = 2500;
await Task.Delay(timeOut);
Console.WriteLine(timeOut);
return nameof(SecondTask) + timeOut;
}
}
頁
@page "/task-test"
@inject ITaskService _taskService
<h3>TaskTest</h3>
<p>First task: @_firstString</p>
<p>Second task: @_secondString</p>
@code {
private string _firstString = "Init value";
private string _secondString = "Init value";
protected override async Task OnInitializedAsync()
{
var firstTask = _taskService.FirstTask();
var secondTask = _taskService.SecondTask();
await Task.WhenAll(firstTask, secondTask);
_firstString = firstTask.Result;
_secondString = secondTask.Result;
}
}
類似於 Henk 的答案,但用於比較的語法不同。
protected override Task OnInitializedAsync()
{
var firstTask = _taskService.FirstTask()
.ContinueWith(t=> {
_firstString=t.Result;
StateHasChanged();
});
var secondTask = _taskService.SecondTask()
.ContinueWith(t=> {
_secondString = t.Result;
StateHasChanged();
});
return Task.WhenAll(firstTask, secondTask);
}
當FirstTask()
總是首先完成時,您可以像@KirkWoll 評論的那樣簡化您的方法。 看起來像這樣:
protected override async Task OnInitializedAsync()
{
_firstString = await _taskService.FirstTask();
StateHasChanged();
_secondString = await _taskService.SecondTask();
}
我有一個解決方案可以獨立地等待兩者。 雖然不是很漂亮。
protected override async Task OnInitializedAsync()
{
var firstTask = async () =>
{ _firstString = await _taskService.FirstTask();
StateHasChanged();
};
var secondTask = async () =>
{ _secondString = await _taskService.SecondTask();
StateHasChanged();
};
await Task.WhenAll(firstTask(), secondTask()); // note the ()
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.