程序在收到异步结果之前结束

Program ends before async result is received

我正在编写一个程序来通过命令行与 Spotify API 交互。

我这里有一些代码可以接受命令,然后执行相关函数从 Spotify 检索数据。

这段代码说明了问题所在,我已经省略了不相关的代码。

public class CommandHandler
{
    public async void HandleCommands()
    {
        var spotifyCommand = GetCommand();

        if (spotifyCommand == SpotifyCommand.Current)
        {
            WriteCurrentSong(await new PlayerController().GetCurrentlyPlayingAsync());
        }

        if (spotifyCommand == SpotifyCommand.NextTrack)
        {
            WriteCurrentSong(await new PlayerController().NextTrackAsync());
        }

        Console.ReadLine();
        //end of program
    }
}

public class PlayerController
{
    public async Task<SpotifyCurrentlyPlaying> NextTrackAsync()
    {
        using (var httpClient = new HttpClient())
        {
            //removed code to set headers etc

            //Skip Track
            var response = await httpClient.PostAsync("https://api.spotify.com/v1/me/player/next", null);

            if (response.StatusCode != HttpStatusCode.NoContent)
            {
                //code to handle this case, not important
            }
            
            return await GetCurrentlyPlayingAsync();
        }
    }

    public async Task<SpotifyCurrentlyPlaying> GetCurrentlyPlayingAsync()
    {
        using (var httpClient = new HttpClient())
        {
            //removed code to set headers etc
            
            var response = await httpClient.GetAsync("https://api.spotify.com/v1/me/player/currently-playing");

            response.EnsureSuccessStatusCode();

            return JsonSerializer.Deserialize<SpotifyCurrentlyPlaying>(await response.Content.ReadAsStringAsync());
        }
    }
}

HandleCommands() 中的两个 if 语句调用 PlayerController 并等待该方法的结果。出于某种原因,如果我使用 await PlayerController.MethodCall() 进行调用,但是,在程序完成执行之前结果不会 return。

奇怪的是,如果我使用 PlayerController.MethodCall().Result,这不是问题。

任何帮助将不胜感激,因为我真的不想使用 .Result。谢谢!

HandleCommands 的签名有问题

public async void HandleCommands()
{ 
  // ...
}

你没有展示这个方法是如何调用的,但我假设它是这样的:

var handler = new CommandHandler();
handler.HandleCommands();

因为 async void 方法没有 return Task 并且调用者无法“观察”它的完成。
因此应用程序无需等待任务完成即可完成。

修复 - 将方法签名更改为以下并等待任务完成

public async Task HandleCommands()
{ 
  // ...
}

var handler = new CommandHandler();
await handler.HandleCommands();