我在 Windows 8“Metro”应用程序中有一个按钮和一个文本 block 。单击按钮时,它会通过 HttpWebRequest 调用网络服务。
private void buttonGo_Click(object sender, RoutedEventArgs e)
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost/");
req.BeginGetResponse(ResponseCallback, req);
}
private void ResponseCallback(IAsyncResult asyncResult)
{
HttpWebRequest req = (HttpWebRequest)asyncResult.AsyncState;
HttpWebResponse res = (HttpWebResponse)req.EndGetResponse(asyncResult);
Stream streamResponse = res.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string responseString = streamRead.ReadToEnd();
info.Text = responseString; // Can't do this as outside the UI thread
}
我想用从 WebRequest 返回的数据更新 info.Text
,但是它会导致错误:“应用程序调用了一个为不同线程编码的接口(interface)。” 我知道这是因为它不是从 UI 线程调用的。
我发现了各种不同的解决方案,涉及 Dispatcher
、SynchronizationContext
、await
关键字。
最简单/最好的方法是什么?
最佳答案
正如 Damir 所说,我们确实应该使用异步/等待模式,但有时只需要在工作线程(任务)中更新 UI。这是使用当前的 CoreDispatcher 将调用分派(dispatch)到 UI 线程来完成的:
private void ResponseCallback(IAsyncResult asyncResult)
{
...
this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
info.Text = responseString;
});
}
关于c# - 从 Windows 8/WinRT 中的不同线程更新 UI 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13617306/