Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dispatcher.Invoke() on Windows Phone 7?

In a callback method I am attempting to get the text property of a textBox like this:

string postData = tbSendBox.Text;

But because its not executed on the UI thread it gives me a cross-thread exception.

I want something like this:

Dispatcher.BeginInvoke(() =>
{
    string postData = tbSendBox.Text;
});

But this runs asynchronously. The synchronous version is:

Dispatcher.Invoke(() =>
{
    string postData = tbSendBox.Text;
});

But Dispatcher.Invoke() does not exist for the Windows Phone. Is there something equivalent? Is there a different approach?

Here is the whole function:

public void GetRequestStreamCallback(IAsyncResult asynchronousResult)
    {
        HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;

        // End the operation
        Stream postStream = request.EndGetRequestStream(asynchronousResult);

        string postData = tbSendBox.Text;

        // Convert the string into a byte array.
        byte[] byteArray = Encoding.UTF8.GetBytes(postData);

        // Write to the request stream.
        postStream.Write(byteArray, 0, postData.Length);
        postStream.Close();

        // Start the asynchronous operation to get the response
        request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
    }
like image 534
Lemontongs Avatar asked Dec 21 '22 06:12

Lemontongs


1 Answers

No you are right you can access only to the async one. Why do you want sync since you are on a different thread of the UI one?

Deployment.Current.Dispatcher.BeginInvoke(() =>
       {
            string postData = tbSendBox.Text;
        });
like image 66
MatthieuGD Avatar answered Feb 08 '23 20:02

MatthieuGD