简体   繁体   中英

GetStringAsync timeout has no effect

I have the following code:

public static string createRequest(string url, int timeout = 1)
{

    Task<string> responseString;

    using (var client = new System.Net.Http.HttpClient())
    {
        responseString = client.GetStringAsync(url);
        responseString.Wait(new TimeSpan(0, 0, timeout));
    }
}

If I run this code the first time in the debugger, the timeout will occure only after a long while (1-2 minutes). The second time it's running way faster and finishes after round about 3-4 seconds.

If i put a break point on some code after this invokation, it's sometimes running faster but mainly it takes a long while.

Why is the code taking such a long timespan even though there's a defined timeout?

In fact responseString.Status is TaskStatus.Canceled which is exactly what I expect (no device bound to this IP).

What is wrong with this code? Thank you :)

You should not set the timeout of the Task<string> object. You have to set HttpClient.Timeout . Also, please consider using an async/await approach:

public static async Task<string> createRequest(string url, int timeout = 1)
{
     using(var client = new HttpClient())
     {
          client.Timeout = TimeSpan.FromSeconds(timeout);
          string response = await client.GetStringAsync(url);

          // Handle response here

          return handledResponse; // You can return a raw string
     }
}

Probably not the most beautyful version but exactly doing what I expected:

    public string AsyncRequest(string url, int timeout)
    {
        string retval = null;

        using (var client = new System.Net.Http.HttpClient())
        {
            client.Timeout = TimeSpan.FromSeconds(timeout);
            try
            {
                retval = client.GetStringAsync(url).Result;

                return retval;
            }
            catch
            {
                AllnetALL3073RemoteSwitch_found = false;

                return null;
            }
        }
    }

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