Question

I am using the following class for asynchronous calls to a remote server.

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

The method that I call is:

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
          });
    }

From the calling code I process the result using the following code:

 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();
    }

So UserLogin calls the webservice and shows the progress indicator and in the HttpWebRequestCallback I want to show a message box to the user if there is an error and hide the progress indicator.

When that happens I get an error "Cross-thread operation not valid" when I try to show the message box or do this.HideProgressIndicator();

I understand that the UI thread is different and I cannot access it from the HttpWebRequestCallback but I am not sure how to achieve my requirements otherwise.

Can you please suggest what should I do?

Was it helpful?

Solution

In WPF applications I use something like the following, only with Invoke instead of BeginInvoke. As I understand, Invoke does not exist for Windows Phone, so the following should work:

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

this.Dispatcher.BeginInvoke((Action)delegate()
{
    this.HideProgressIndicator();
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top