NewsAPI C# library runs on console, hangs on winforms
Someone asked on Stack Overflow:
I ran the example given at the web site under Visual Studio 2017 Community Edition and it worked fine. However, when I attempted to run it on a winforms library, it hung, even when given the exact same term:
Console Version
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 hereWinforms Version
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) {
I posted the following answer, which was chosen as the accepted answer and received 1 upvote:
Assuming that you’re using this client, the method you’re calling uses a Task.Result which can cause a deadlock. Seems reasonable, since the code/signature and examples match.
I would rewrite your code like this for WinForms:
private async void btnSearch_Click(object sender, EventArgs e)
{
var newsApiClient = new NewsApiClient("keyredacted");
var articleResponse = await newsApiClient.GetEverythingAsync(new EverythingRequest
...
If you are deadset on not using the async methods in your code you could try running it inside of a Task.Run(() => /* stuff */);
Originally posted on Stack Overflow — 1 upvotes (accepted answer). Licensed under CC BY-SA.