Dispatcher.Invoke() on Windows Phone 7?

坚强是说给别人听的谎言 提交于 2019-12-22 09:00:40

问题


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

回答1:


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



回答2:


This should make an asynchronous call to a synchronous :

  Exception exception = null;
  var waitEvent = new System.Threading.ManualResetEvent(false);
  string postData = "";
  Deployment.Current.Dispatcher.BeginInvoke(() =>
  {
    try
    {
      postData = tbSendBox.Text;
    }
    catch (Exception ex)
    {
      exception = ex;
    }
    waitEvent.Set();
  });
  waitEvent.WaitOne();
  if (exception != null)
    throw exception;



回答3:


1) Obtain a reference to the synchronization context of UI thread. For example,

SynchronizationContext context = SynchronizationContext.Current

2) Then post your callback to this context. This is how Dispatcher internally works

context.Post((userSuppliedState) => { }, null);

Is it what you want?



来源:https://stackoverflow.com/questions/8004252/dispatcher-invoke-on-windows-phone-7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!