12

Blazor と C# 8.0 の IAsyncEnumerable 機能をいじっています。Razor Pages 内で IAsyncEnumerable を使用して await を使用して、データを含むマークアップを段階的に表示することは可能ですか?

サービス例:

private static readonly string[] games = new[] { "Call of Duty", "Legend of Zelda", "Super Mario 64" };
public async IAsyncEnumerable<string> GetGames()
{
   foreach (var game in games)
   {
     await Task.Delay(1000);
     yield return game;
   }
}

カミソリページの例:

@await foreach(var game in GameService.GetGames())
{
  <p>@game</p>
}

これにより、エラー CS4033 が発生します: 'await' 演算子は、非同期メソッド内でのみ使用できます。このメソッドを「async」修飾子でマークし、戻り値の型を「Task」に変更することを検討してください。

これが可能であれば、何かアイデアはありますか?

4

2 に答える 2

5

テンプレート コードawait foreachには記述できません。ただし、回避策として、次のセクション.razorに記述できます。@code

@if (@gamesUI == null)
{
    <p><em>Loading...</em></p>
}
else
{
    <table class="table">
        <thead>
            <tr>
                <th>Game</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var game in gamesUI)  // <--- workaround
            {
                <tr>
                    <td>@game</td>
                </tr>
            }
        </tbody>
    </table>
}

@code {
    List<string> gamesUI;  // <--- workaround

    protected override async Task OnInitializedAsync()
    {
        gamesUI = new List<string>();
        await foreach(var game in GService.GetgamesAsync() )
        {
            gamesUI.Add(game);
            this.StateHasChanged();
        }
    }
}

効果:

ここに画像の説明を入力

収量データ:

        private static readonly string[] games = new[] { "Call of Duty", "Legend of Zelda", "Super Mario 64", "Bag man" };


        public async IAsyncEnumerable<string> GetgamesAsync()
        {
            var rng = new Random();

            foreach (var game in games)
            {
                await Task.Delay(1000);
                yield return game;
            }
        }
于 2019-09-10T14:11:46.557 に答える