调用ExecuteAsync()函数时异步任务死锁

时间:2018-08-06 07:51:05

标签: c# api model-view-controller async-await youtube-api

当我尝试从任务async函数的函数返回任务结果时遇到问题:

public async Task<IEnumerable<string>> Run()
        {
            var youtubeService = new YouTubeService(new BaseClientService.Initializer()
            {
                ApiKey = "API Key",


  ApplicationName = this.GetType().ToString()
        });

        var searchListRequest = youtubeService.Search.List("snippet");
        searchListRequest.Q = "anwar jibawi"; // Replace with your search term.
        searchListRequest.MaxResults = 50;

        // Call the search.list method to retrieve results matching the specified query term.
        var searchListResponse = await searchListRequest.ExecuteAsync();

        List<string> videos = new List<string>();
        List<string> channels = new List<string>();
        List<string> playlists = new List<string>();

        // Add each result to the appropriate list, and then display the lists of
        // matching videos, channels, and playlists.
        foreach (var searchResult in searchListResponse.Items)
        {
            switch (searchResult.Id.Kind)
            {
                case "youtube#video":
                    string thumbnail = searchResult.Snippet.Thumbnails.Default__.Url;
                    videos.Add(String.Format("{0} ({1}) {2}", searchResult.Snippet.Title, searchResult.Id.VideoId, thumbnail));
                    break;

                case "youtube#channel":
                    channels.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.ChannelId));
                    break;

                case "youtube#playlist":
                    playlists.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.PlaylistId));
                    break;
            }
        }

        return videos;
        //Console.WriteLine(String.Format("Videos:\n{0}\n", string.Join("\n", videos)));
        //Console.WriteLine(String.Format("Channels:\n{0}\n", string.Join("\n", channels)));
        //Console.WriteLine(String.Format("Playlists:\n{0}\n", string.Join("\n", playlists)));
    }

在这里我调用异步函数:

public ActionResult Index()
    {

        Task<IEnumerable<string>> task = new Search().Run();
        task.Wait();//if remove this line it will work fine but without any result
        var x = task.Result;//if remove this line it will work fine but without any result
        return View();
    }

为什么我打电话给task.Wait()task.Reslut时挂起

1 个答案:

答案 0 :(得分:2)

假设这是一个ASP.NET应用程序,you shouldn't use .Result(或SELECT * FROM dbo.ViewAllLog VAL WHERE ViewAllLogId IN ( SELECT MAX(ViewAllLogId) as ViewAllLogId FROM dbo.ViewAllLog VAL WHERE VAL.UserLocation IN ('hci') and VAL.status IN ('DRPL','DRPE') --AND ISNULL(VAL.tractor,'') <> '' GROUP BY VAL.UserLocation, VAL.orderNumber ) )将导致死锁(如您所知)

相反,将您的Index方法更改为此

.Wait()
相关问题