Xamarin:将超时设置为webrequest任务

时间:2014-05-15 10:23:12

标签: c# android xamarin

我的功能如下:

public static Task<string> MakeAsyncRequest(string url, string contentType)
        {
            LogMe (TAG, url);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.ContentType = contentType;
            request.Method = WebRequestMethods.Http.Get;
            request.Timeout = 200000;
            request.Proxy = null;


            Task<WebResponse> task = Task.Factory.FromAsync(
                request.BeginGetResponse,
                asyncResult => request.EndGetResponse(asyncResult),
                (object)null);
            return task.ContinueWith(t => ReadStreamFromResponse(t.Result));
        }

那么,如何为这个tasK设置超时?
例如,10秒后,此任务取消,吐司说&#34;连接超时&#34;
我是C#的初学者 请协助。

2 个答案:

答案 0 :(得分:0)

使用此功能时,该功能的时间为20000ms =超时20秒。

此函数执行请求的响应。使用此代码读取响应。

private static string ReadStreamFromResponse(WebResponse response)
    {

        using (Stream responseStream = response.GetResponseStream())
        using (StreamReader sr = new StreamReader(responseStream))
        {
            //Need to return this response 
            strContent = sr.ReadToEnd();
        }
        return strContent;

    }

我猜这有助于你。

我正在处理相同的代码,如果您需要请问我。

自从Renan costella

答案 1 :(得分:-1)

  

CountDownTimer counter = new CountDownTimer(1000 * 10,0){

     

@Override public void onTick(long millisUntilFinished){}

     

@覆盖
  public void onFinish(){

          // finish that task

    } 
     

};

在MakeAsyncRequest(...)之前调用下面的methode;

  

counter.start();

相关问题