簡體   English   中英

如果互聯網速度慢並且數據在10秒內沒有收集,我怎樣才能停止httprequest?

[英]how can I make the httprequest stop if internet is slow and data is not gather within 10 seconds?

當我使用緩慢的互聯網處理我的應用程序時,當我按下通過httprequests收集數據的不同按鈕時,我會崩潰。 我怎么能創建一個函數,以便如果我不在10秒內收到數據,那么應該取消從httprequest收集數據的嘗試。

這是我的代碼:

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

        }
   }

你可以使用CancellationTokenSource ,它有一個提供的方法,即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 ();

這是一篇關於使用GetAsync取消的文章,您可能有興趣閱讀。

您還可以在httpclient上使用超時。

        var httpClientRequest = new HttpClient();
        httpClientRequest.Timeout = TimeSpan.FromSeconds(10);
        var result = await httpClientRequest.GetAsync("http://localhost");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM