我运行了Visual Studio 2017 Community Edition网站上给出的示例,它运行良好。但是,当我尝试在winforms库上运行它时,即使给出了完全相同的术语,它也会挂起:
控制台版本
static void Main(string[] args)
{
var newsApiClient = new NewsApiClient("KeyRedacted");
var articlesResponse = newsApiClient.GetEverything(new EverythingRequest
{
Q = "Apple",
SortBy = SortBys.Popularity,
Language = Languages.EN,
From = new DateTime(2018, 10, 16)
});
if (articlesResponse.Status == Statuses.Ok)
{
//code here
Winforms版本
private void btnSearch_Click(object sender, EventArgs e)
{
var newsApiClient = new NewsApiClient("keyredacted");
var articleResponse = newsApiClient.GetEverything(new EverythingRequest
{
Q = "Apple",
SortBy = SortBys.Popularity,
Language = Languages.EN,
From = new DateTime(2018, 10, 16)
}); //this is where it hangs
if (articleResponse.Status == Statuses.Ok)
{
答案 0 :(得分:1)
假设您正在使用this client,则method you're calling使用的Task.Result
可以cause a deadlock。似乎合理,因为代码/签名和示例匹配。
我会像这样为WinForms重写代码:
private async void btnSearch_Click(object sender, EventArgs e)
{
var newsApiClient = new NewsApiClient("keyredacted");
var articleResponse = await newsApiClient.GetEverythingAsync(new EverythingRequest
...
如果您不愿意在代码中不使用异步方法,可以尝试在Task.Run(() => /* stuff */);
内运行它