[英]How to stop webrequest in windows phone 8.1 c#
I have just started developing an application targeting windows phone 8.1. 我刚刚开始开发针对Windows Phone 8.1的应用程序。 In my application I am calling my web service and getting results from it.
在我的应用程序中,我正在调用Web服务并从中获取结果。 But when i click the hardware back button while the web request is processing the page is redirecting to the previous page, but I couldn't stop processing the Web request.
但是,当我在Web请求处理过程中单击硬件后退按钮时,该页面将重定向到上一页,但是我无法停止处理Web请求。 The result is getting displayed when it got the response.
得到响应后将显示结果。
My code is here: 我的代码在这里:
private async void accAcctDet_Click(object sender, RoutedEventArgs e)
{
string selected = acct[cmbAccDetail.SelectedIndex];
string maskselect = cmbAccDetail.SelectedItem.ToString();
prog.Visibility = Visibility.Visible;
acctdetails obj = new acctdetails();
var result = await obj.GetToken(selected);
if (result.Substring(0, 2) == "Se" || result.Substring(0, 2) == "Ki")
{
prog.Visibility = Visibility.Collapsed;
MessageDialog msgbox = new MessageDialog("Service Unavailable. Please try again later", "e-Book!");
await msgbox.ShowAsync();
ContentRoot.Visibility = Visibility.Visible;
myCommandBar.Visibility = Visibility.Visible;
}
else
{
prog.Visibility = Visibility.Collapsed;
this.Frame.Navigate(typeof(acctdetinfo), result);
}
}
public async Task<string> GetToken(string selected)
{
string postData = "selAcct=" + selected;
var res = await post("myparameter", postData);
return res;
}
private async Task<string> post(string url, string postdata)
{
var request = WebRequest.Create(new Uri("myurl.com" + url)) as HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/json";
byte[] data = Encoding.UTF8.GetBytes(postdata);
//request.ContentLength = data.Length;
using (var requestStream = await Task<Stream>.Factory.FromAsync(request.BeginGetRequestStream, request.EndGetRequestStream, request))
{
await requestStream.WriteAsync(data, 0, data.Length);
}
WebResponse responseObject = await Task<WebResponse>.Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, request);
var responseStream = responseObject.GetResponseStream();
var sr = new StreamReader(responseStream);
string received = await sr.ReadToEndAsync();
return received;
}
I need to stop the request once the user clicked the hardware back button. 用户单击硬件后退按钮后,我需要停止该请求。
Any help would be highly appreciated 任何帮助将不胜感激
You could either add a bool
to check if the user has navigated away 您可以添加一个
bool
来检查用户是否已离开
//Inside OnNavigatingFrom
...
hasNavigatedAway = true;
...
//Inside post(string url, string postdata)
if(hasNavigatedAway) return;
or you can do something with a CancellationToken
as answered here . 或者,您也可以使用
CancellationToken
来执行某些操作,如此处所示 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.