Dispatcher.Invoke () on Windows Phone 7?

In the callback method, I am trying to get the text property textBox as follows:

string postData = tbSendBox.Text; 

But since it is not running in the UI thread, it gives me an exception for cross threads.

I need something like this:

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

But this is done asynchronously. Synchronous version:

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

But Dispatcher.Invoke () does not exist for Windows Phone. Is there something equivalent? Is there any other 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); } 
+4
source share
3 answers

No, you are right, you can only access asynchronous. Why do you want to sync since you are using a different user interface thread?

 Deployment.Current.Dispatcher.BeginInvoke(() => { string postData = tbSendBox.Text; }); 
+9
source

This should make the asynchronous call 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; 
+2
source

1) Get a link to the user interface thread synchronization context. For instance,

 SynchronizationContext context = SynchronizationContext.Current 

2) Then send your callback to this context. So Dispatcher works inside

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

Is this what you want?

0
source

Source: https://habr.com/ru/post/1379579/


All Articles