问题
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