这是我在 Windows 应用商店应用论坛中的问题的重复:
我有一个等待的方法返回一个任务。它通过了指定的代表做出决定。该任务遍历一些对象并调用委托以确定是否应该处理一个对象。在经典的 .NET 中,我将按如下方式实现:
private Task ProcessDemo(Func<int, bool> processDecisionHandler)
{
// Get the current SynchronizationContext
SynchronizationContext synchronizationContext = SynchronizationContext.Current;
return Task.Run(() =>
{
for (int i = 0; i < 10; i++)
{
// Invoke the process decision handler in the UI thread
bool process = false;
synchronizationContext.Send((state) => { process = processDecisionHandler(i); }, i);
if (process)
{
// Process the item
...
}
}
});
}
可以像这样调用此方法:
private async void testButton_Click(object sender, RoutedEventArgs e)
{
this.WriteLine("UI-Thread ({0})", Thread.CurrentThread.ManagedThreadId);
Func<int, bool> handler = (i) =>
{
if (MessageBox.Show("Process " + i + "?", this.Title, MessageBoxButton.YesNo, MessageBoxImage.Information) == MessageBoxResult.Yes)
{
return true;
}
else
{
return false;
}
};
await this.ProcessDemo(handler);
}
在 Windows Store Apps 中,我面临 SynchronizationContext 的 Send 方法不可用的问题。Post 显然对我的目标不起作用,因为我必须“等待”处理程序结果。
如果没有 Dispatcher(我在库代码中没有),我怎么能实现我的目标?