在windows phone app中调用webservice时如何增加超时?

时间:2015-09-23 06:18:39

标签: windows-phone-8 windows-phone-8.1 settimeout timeoutexception

我开发了一个Windows手机app.but应用程序因超时异常而崩溃。如何处理此超时异常。请帮助我。下面是我的代码:

  public async void Login()
        {


     var client = new NewReloadApp.JsonWebClient();

      var resp = await client.DoRequestAsync(Url.weburl + "Validateuser_v2?Emailid=" + Emailid.Text + "&Password=" + password.Password + "&DeviceID=" + deviceid + "&PlatformID=7&DeviceToken=windowsReload&Mobilemodel=nokia&Appversion=1.4.14&MobileOS=windows");

                string result = resp.ReadToEnd();

                JObject obj = JObject.Parse(result);
}

我没有使用任何httpwebrequest方法。在上面的代码中我尝试设置超时属性,但我无法获得任何超时方法。请帮助我如何设置上述代码的超时。

下面是我的jsonwebclient类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace NewReloadApp
{
    class JsonWebClient
    {

        public async Task<T> DoRequestJsonAsync<T>(WebRequest req)
        {
            var ret = await DoRequestAsync(req);
            var response = await ret.ReadToEndAsync();
            return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(response);
        }

        public async Task<T> DoRequestJsonAsync<T>(string uri)
        {
            var ret = await DoRequestAsync(uri);
            var response = await ret.ReadToEndAsync();
            return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(response);
        }

        public async Task<System.IO.TextReader> DoRequestAsync(WebRequest req)
        {
            var task = Task.Factory.FromAsync((cb, o) => ((HttpWebRequest)o).BeginGetResponse(cb, o), res => ((HttpWebRequest)res.AsyncState).EndGetResponse(res), req);
            var result = await task;
            var resp = result;
            var stream = resp.GetResponseStream();
            var sr = new System.IO.StreamReader(stream);
            return sr;
        }

        public async Task<System.IO.TextReader> DoRequestAsync(string url)
        {
            HttpWebRequest req = HttpWebRequest.CreateHttp(url);
            req.AllowReadStreamBuffering = true;
            var tr = await DoRequestAsync(req);
            return tr;
        }
    }

}

1 个答案:

答案 0 :(得分:1)

  

使用CancellationToken:

我尝试但是它可能对你有帮助。

public async Task<System.IO.TextReader> DoRequestAsync(string url)
    {
        CancellationTokenSource ct= new CancellationTokenSource(2000); //2 
        HttpWebRequest req = HttpWebRequest.CreateHttp(url);
        req.AllowReadStreamBuffering = true;
        var tr = await DoRequestAsync(req).AsTask(ct.Token);;
        return tr;
    }

如此post

中所述