Windows phone 7 Windows Phone 7上的Dispatcher.Invoke()?

Windows phone 7 Windows Phone 7上的Dispatcher.Invoke()?,windows-phone-7,dispatcher,Windows Phone 7,Dispatcher,在回调方法中,我尝试获取文本框的text属性,如下所示: string postData = tbSendBox.Text; Dispatcher.BeginInvoke(() => { string postData = tbSendBox.Text; }); 但是因为它不是在UI线程上执行的,所以它给了我一个跨线程异常 我想要这样的东西: string postData = tbSendBox.Text; Dispatcher.BeginInvoke(() => {

在回调方法中,我尝试获取文本框的text属性,如下所示:

string postData = tbSendBox.Text;
Dispatcher.BeginInvoke(() =>
{
    string postData = tbSendBox.Text;
});
但是因为它不是在UI线程上执行的,所以它给了我一个跨线程异常

我想要这样的东西:

string postData = tbSendBox.Text;
Dispatcher.BeginInvoke(() =>
{
    string postData = tbSendBox.Text;
});
但这是异步运行的。同步版本为:

Dispatcher.Invoke(() =>
{
    string postData = tbSendBox.Text;
});
但Windows Phone不存在Dispatcher.Invoke()。有类似的东西吗?有不同的方法吗

以下是整个功能:

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

不,你是对的,你只能访问异步的。既然您在UI one的不同线程上,为什么要同步

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

这将对同步进程进行异步调用:

  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;
1) 获取对UI线程的同步上下文的引用。比如说,

SynchronizationContext context = SynchronizationContext.Current
2) 然后将回调发布到此上下文。这就是Dispatcher内部的工作方式

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

这是您想要的吗?

因为我需要将postData变量设置为文本框的文本,然后才能继续执行函数的其余部分。我想我的总体问题是:如何从非UI线程的线程获取UI属性。或者,如何使用参数调用回调函数,即:
myReq.BeginGetRequestStream(新的异步回调(GetRequestStreamCallback**arguments??**),myReq)我认为它违背了Windows Phone异步模型的目的:UI优先于所有其他后台任务,以防止用户体验不好(渲染速度慢等)。也许你可以通过显示诸如“加载”或“更新”之类的mesage来缓解……我试过了。这似乎有道理,但该线程在分派到另一个线程之前在WaitOne()上被阻塞,因此它永远不会到达Set()@Lemontongs,你错了。如果您在非ui线程中执行此代码,它将根据您的需要工作。。另外,我在程序中使用此代码进行同步操作。