简体   繁体   English

等待任务完成异步httpwebrequest

[英]Wait for task to complete async httpwebrequest

Hi i have the following code, which I'm calling from my UI in windows phone 8. 嗨,我有以下代码,我是从Windows Phone 8的UI中调用的。

    public void GetToken()
    {
        string postData = "username=" + NTUser.username + "&appId=" + appId + "&signed=" + CreateSignedHex();

        post("authorize?", postData);
    }

    private async Task<string> post(string url, string postdata)
    {
        var request = WebRequest.Create(new Uri(apiUrl + url)) as HttpWebRequest;
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        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;
    }

And i have this code to run in my UI -> 我有这段代码可以在我的UI中运行->

    private void Login_Click(object sender, RoutedEventArgs e)
    {


        ProgressIndicator progress = new ProgressIndicator
        {
            IsVisible = true,
            IsIndeterminate = true,
            Text = "Downloading details..."
        };
        SystemTray.SetProgressIndicator(this, progress);


        string userName = uiTextBoxUsername.Text;







        UserController uC = new UserController(userName, null);

        uC.GetToken();

       //HERE needs the logic which check whether the httpwebrequest task is completed
       //Proceed to another page
  }

I want from my UI to be able to check when the httpwebrequest task is completed, and in the meanwhile just show a progressindicator. 我希望从我的UI中能够检查httpwebrequest任务何时完成,同时仅显示一个progressindicator。

Thanks in advance. 提前致谢。

Rewrite GetToken like this: 像这样重写GetToken:

public async Task GetToken()
{
    string postData = "username=" + NTUser.username + "&appId=" + appId + "&signed=" + CreateSignedHex();

    await post("authorize?", postData);
}

and call it like this: 并这样称呼它:

await uC.GetToken();
// and now hide the progressindicator and proceed to the other page

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM