c# - 从 Windows 8/WinRT 中的不同线程更新 UI 元素

标签 c# asynchronous windows-8 windows-runtime

我在 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 线程调用的。

我发现了各种不同的解决方案,涉及 DispatcherSynchronizationContextawait 关键字。

最简单/最好的方法是什么?

最佳答案

正如 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/

相关文章:

c# - Google 在哪里使用 C#

c# - 当我调用 BeginXXX() 时,CLR 何时创建 IO 线程

c# - 我可以使用 CancellationToken 取消 StreamReader.ReadLineAsync 吗?

html - Windows 8 WinJS 应用程序 CSS 未按预期运行

javascript - 如何关闭 javascript metro 风格的应用程序?

c# - C# 中 HTML 换行符的常量?

c# - NHibernate 带来旧数据

javascript - 为 Mongodb 创建多个动态对象 NodeJs 查询

.net - WPF弹出窗口的习惯

c# - Entity Framework Brainmush Kerfuffle 壮观