跨线程操作在PostAsync回调时无效

时间:2014-05-13 09:19:30

标签: asynchronous windows-phone

我使用以下类来对远程服务器进行异步调用。

http://www.matlus.com/httpwebrequest-asynchronous-programming/

我打电话的方法是:

public static void PostAsync(string url, Dictionary<string, string> postParameters,
      Action<HttpWebRequestCallbackState> responseCallback, object state = null,
      string contentType = "application/json")
    {
        var httpWebRequest = CreateHttpWebRequest(url, "POST", contentType);
        var requestBytes = GetRequestBytesPost(postParameters);
        httpWebRequest.ContentLength = requestBytes.Length;

        httpWebRequest.BeginGetRequestStream(BeginGetRequestStreamCallback,
          new HttpWebRequestAsyncState()
          {
              RequestBytes = requestBytes,
              HttpWebRequest = httpWebRequest,
              ResponseCallback = responseCallback,
              State = state
          });
    }

从调用代码我使用以下代码处理结果:

 private void UserLogin()
    {

        var postParameters = new Dictionary<string, string>();


        postParameters.Add("Email", tbEmailAddress.Text);
        postParameters.Add("Password", tbPassword.Password);

        HttpSocket.PostAsync("URL", postParameters, HttpWebRequestCallback, null);

        this.ShowProgressIndicator();

    }

    private void HttpWebRequestCallback(HttpWebRequestCallbackState callbackState)
    {

        if (callbackState.Exception != null)
        {
            MsgBox.Show("Error message");
        }
        else
        {
           // do work
        }    

        this.HideProgressIndicator();
    }

所以UserLogin调用web服务并显示进度指示器,在HttpWebRequestCallback中,如果出现错误并隐藏进度指示器,我想向用户显示一个消息框。

当发生这种情况时,当我尝试显示消息框或执行此操作时,我收到错误“跨线程操作无效”.HideProgressIndicator();

我知道UI线程不同,我无法从HttpWebRequestCallback访问它,但我不知道如何实现我的要求。

你能告诉我该怎么办?

1 个答案:

答案 0 :(得分:0)

在WPF应用程序中,我使用以下内容,仅使用Invoke而不是BeginInvoke。据我了解,Windows Phone不存在Invoke,因此以下内容应该有效:

if (callbackState.Exception != null)
{
    this.Dispatcher.BeginInvoke((Action)delegate()
    {
        MsgBox.Show("Error message");
    });
}
else
{
    // do work
}    

this.Dispatcher.BeginInvoke((Action)delegate()
{
    this.HideProgressIndicator();
});
相关问题