【发布时间】:2013-07-16 17:07:10
【问题描述】:
我正在使用 Dispatcher.RunAsync() 从后台线程显示 MessageDialog。但我无法弄清楚如何返回结果。
我的代码:
bool response = false;
await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
async () =>
{
DebugWriteln("Showing confirmation dialog: '" + s + "'.");
MessageDialog dialog = new MessageDialog(s);
dialog.Commands.Add(new UICommand(GetLanguageString("Util_DialogButtonYes"), new UICommandInvokedHandler((command) => {
DebugWriteln("User clicked 'Yes' in confirmation dialog");
response = true;
})));
dialog.Commands.Add(new UICommand(GetLanguageString("Util_DialogButtonNo"), new UICommandInvokedHandler((command) =>
{
DebugWriteln("User clicked 'No' in confirmatoin dialog");
response = false;
})));
dialog.CancelCommandIndex = 1;
await dialog.ShowAsync();
});
//response is always False
DebugWriteln(response);
有没有办法做到这一点? 我想过可能会从 RunAsync() 内部返回值,但函数是无效的。
【问题讨论】:
-
你应该尽量避免
CoreDispatcher.RunAsync。该方法使您的 UI 线程像您的后台线程使用的“服务”。更简洁的设计是让您的后台线程成为您的 UI 线程使用的“服务”。那么你只需要async/await并且根本不需要手动调度委托。 -
我必须同意斯蒂芬的观点。我发布的代码来自用 VS2010 编写的 SL 应用程序,因此我无法访问
async/await(一旦我开始在 VS2012 中开发新的 SL 应用程序,我发现该方法没有用处)。也就是说,在另一个线程中不时地从 UI 中获取偶尔的文本框值或其他内容仍然是有益的。
标签: c# .net windows-store-apps