等待事件发生以调用另一种方法?

时间:2019-07-17 17:15:23

标签: c#

我遇到了一个问题,我正在尝试根据此仓库创建一个程序:https://github.com/JohnnyCrazy/SpotifyAPI-NET

它是围绕Spotify API的C#包装器。

我正在尝试创建一个关注点分离,我希望程序在调用Api之前等待AuthOnAuthReceived方法。

using SpotifyAPI.Web;
using SpotifyAPI.Web.Auth;
using SpotifyAPI.Web.Enums;
using SpotifyAPI.Web.Models;
using System;
using System.Collections.Generic;
using System.Text;

namespace Spotify_Playlist_Creator
{
        public class SpotifyService
{
    private static string _clientId = "eca82f597115423cac9d1125e0fb97c4";
    private static string _sectretId = "17a6e5916bb3424eb50f29e4816521a4";
    private static SpotifyWebAPI api;
    private static SpotifyService spotifyService;


    private SpotifyService() { }

    public static Task<SpotifyService> GetSpotifyService()
    {
        TaskCompletionSource<SpotifyService> taskCompletionSource = new TaskCompletionSource<SpotifyService>();

        _clientId = string.IsNullOrEmpty(_clientId) ?
        Environment.GetEnvironmentVariable("SPOTIFY_CLIENT_ID") :
        _clientId;

        _sectretId = string.IsNullOrEmpty(_sectretId) ?
           Environment.GetEnvironmentVariable("SPOTIFY_SECRET_ID") :
           _sectretId;

        AuthorizationCodeAuth auth =
        new AuthorizationCodeAuth(_clientId, _sectretId, "http://localhost:4003", "http://localhost:4003",

        Scope.PlaylistModifyPrivate | Scope.PlaylistReadCollaborative);
        auth.AuthReceived += AuthOnAuthReceivedAsync;
        auth.AuthReceived += delegate
        {
            taskCompletionSource.SetResult(spotifyService);
        };

        auth.Start();
        auth.OpenBrowser();



        return taskCompletionSource.Task;
    }


    private async static void AuthOnAuthReceivedAsync(object sender, AuthorizationCode payload)
    {
        AuthorizationCodeAuth auth = (AuthorizationCodeAuth)sender;
        auth.Stop();

        Token token = await auth.ExchangeCode(payload.Code);
        api = new SpotifyWebAPI
        {
            AccessToken = token.AccessToken,
            TokenType = token.TokenType
        };
    }

}

}

如您所见,有一个名为“ GetPlaylists”的方法,该方法仅在AuthOnAuthReceived运行时有效。我希望能够像这样运行调用代码:

    SpotifyService spotifyService = new SpotifyService(_clientId, _secretId);
    Console.WriteLine(spotifyService.GetPlaylist("4l7BpS8kIU6xcmVkijHl5g"));

^^由于身份验证发生速度不够快,此操作失败。如果我可以确保无需将要调用的方法放在事件方法中就可以确保进行身份验证?

0 个答案:

没有答案