1

I get crashes when I work with my app with a slow internet when I keep pressing different buttons that gathers data via httprequests. how could i make a function so that if i do not recieve the data within for example 10 seconds, the attempt to gather the data from the httprequest should be cancelled.

This is my code:

static public async Task<JObject> getCategories ()
    {
        var httpClientRequest = new HttpClient ();
        try {
        var result = await httpClientRequest.GetAsync ("http://localhost");
        var resultString = await result.Content.ReadAsStringAsync ();

        var jsonResult = JObject.Parse (resultString);

        System.Diagnostics.Debug.WriteLine (resultString);

        return jsonResult;
    }

        catch {

            return null;
        }

    }



async void createCategory (object sender, EventArgs args)
{
var getCategory = await parseAPI.getCategories ();

if (getCategory != null) {

foreach (var currentItem in getItems["results"]) {
    id = currentItem ["ID"].ToString ();
    objectid = currentItem ["objectid"].ToString ();

    //connected
    }

  }
        } else {

            //no connection

        }
   }
Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
medvedo
  • 543
  • 2
  • 8
  • 23

2 Answers2

2

You can use CancellationTokenSource which has a method provided in it which is CancelAfter():

 var token = new CancellationTokenSource();
 token.CancelAfter(10000); // after 10 secs
 var result = await httpClientRequest.GetAsync ("http://localhost",token.Token);
 var resultString = await result.Content.ReadAsStringAsync ();

Here is a article about using Cancellation with GetAsync which you may be interested to read.

Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
1

You could also use the timeout on the httpclient.

        var httpClientRequest = new HttpClient();
        httpClientRequest.Timeout = TimeSpan.FromSeconds(10);
        var result = await httpClientRequest.GetAsync("http://localhost");
wishmaster
  • 1,303
  • 8
  • 15
  • should I use the timeout inside the try function? – medvedo May 05 '16 at 22:19
  • Yes of course! It will trigger a TaskCanceledException. – wishmaster May 05 '16 at 22:25
  • Seems like it doesnt work. I made it 1 second just to try it out. And it does not reach the else (//no connection) code after 1 second. – medvedo May 05 '16 at 22:29
  • is the result coming back with something else than null ? You should add a GetAsync ("http://localhost").ConfigureAwait(false) to your Async calls to avoid capturing the current context – wishmaster May 05 '16 at 22:35
  • It returns a result but it takes 5 seconds (for my slow wifi) to recieve it and I have put the timeout to 1 second, so it shouldnt even get a result – medvedo May 05 '16 at 22:48