我正在使用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()内部返回值,但函数是空的。
答案 0 :(得分:3)
您可以使用ManualResetEvent
类。
这是我的帮助方法,用于将值从UI线程返回到其他线程。 这适用于Silverlight!因此,您可能无法将其复制粘贴到您的应用程序并期望它能够正常工作,但希望它能让您了解它如何进行。
public static T Invoke<T>(Func<T> action)
{
if (Dispatcher.CheckAccess())
return action();
else
{
T result = default(T);
ManualResetEvent reset = new ManualResetEvent(false);
Dispatcher.BeginInvoke(() =>
{
result = action();
reset.Set();
});
reset.WaitOne();
return result;
}
}