Reputation: 303
I am developed one windows phone app.but app was crashed due to timeout exception.how to handle this timeout exception.please help me.below is my code:
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);
}
I am not using any httpwebrequest method.in the above code I try to set timeout property but I could not get any timeout method.please help me how to set timeout for the above code.
below is my jsonwebclient class:
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;
}
}
}
Upvotes: 1
Views: 108
Reputation: 106
Use a CancellationToken:
I dint try but it may help you.
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;
}
as mentioned in this post
Upvotes: 1