简体   繁体   中英

NewsAPI C# library runs on console, hangs on winforms

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 here

Winforms 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)
    {

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 */);

See also: https://blogs.msdn.microsoft.com/pfxteam/2012/04/13/should-i-expose-synchronous-wrappers-for-asynchronous-methods/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM