问题描述
我正在使用Dispatcher.RunAsync()从后台线程显示MessageDialog.但是我很难弄清楚如何返回结果.
I'm using Dispatcher.RunAsync() to show a MessageDialog from a background thread. But I'm having trouble figuring out how to get a result returned.
我的代码:
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()内部返回值,但函数无效.
Is there anyway to do it like this?I thought about maybe returning the value from inside RunAsync() but function is void.
推荐答案
您可以使用 ManualResetEvent
类.
这是我的帮助方法,用于将值从UI线程返回到其他线程.这是针对Silverlight的!因此,您可能不能将其复制粘贴到您的应用程序中并期望它能正常工作,但希望它能给您一个思路如何进行.
This is my helper method for returning values from the UI thread to other threads. This is for Silverlight! As such, you probably can't copy-paste it to your application and expect it to work, BUT hopefully it'll give you an idea on how to proceed.
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;
}
}
这篇关于从Dispatcher.RunAsync()返回值到后台线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!