【发布时间】:2019-01-13 03:14:04
【问题描述】:
当我尝试从任务async function my function 返回任务结果时遇到问题:
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 时它会挂起
【问题讨论】:
-
为什么不把方法改成
Task<ActionResult>和await这个任务呢? -
如果我更改了方法,如何返回我的 IEnumerable
视频?有吗?
标签: c# api model-view-controller async-await youtube-api