在Blazor的(异步任务OnInitializedAsync)生命周期中使用两个await不起作用。

huangapple go评论70阅读模式
英文:

Using two await inside the Blazor (async Task OnInitializedAsync) lifecycle doesn't work properly

问题

我正在使用以下方法进行操作。

protected override async Task OnInitializedAsync()
{
    forecasts = await Http.GetJsonAsync<WeatherForecast[]>("sample-data/weather.json");
    await someOperation(); // 此操作未执行
}

对此查询有任何建议吗?

英文:

I am using the following method in an operation.

protected override async Task OnInitializedAsync()
{
    forecasts = await Http.GetJsonAsync&lt;WeatherForecast[]&gt;(&quot;sample-data/weather.json&quot;);
    await someOperation(); // this action is not perfomred
}

Any suggestion on this query

答案1

得分: 1

以下是翻译好的部分:

我以前曾遇到过这个问题,我可以像这样修复它:

protected override async Task OnInitializedAsync()
{
    Http.GetJsonAsync<WeatherForecast[]>("sample-data/weather.json").ContinueWith(task => forecasts = task.Result); //创建一个在目标任务完成时异步执行的延续。

    await someOperation(); //如果需要,此操作也可以使用ContinueWith来完成。
}

ContinueWith 文档:

希望这有所帮助。

英文:

I have had this issue in the past and I was able to fix it like:

protected override async Task OnInitializedAsync()
{
    Http.GetJsonAsync&lt;WeatherForecast[]&gt;(&quot;sample-data/weather.json&quot;).ContinueWith(task =&gt; forecasts = task.Result); //Creates a continuation that executes asynchronously when the target Task completes.


    await someOperation(); // his action can also be done using ContinueWith if needed
}

ContinueWith Doc:

Hope this helps.

huangapple
  • 本文由 发表于 2020年1月3日 17:42:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/59576210.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定