将Dispatcher.RunAsync()中的值返回到后台线程
本文关键字:返回 后台 线程 Dispatcher RunAsync | 更新日期: 2023-09-27 18:22:36
我正在使用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()内部返回值,但函数无效。
您可以使用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;
}
}