我刚刚注意到,使用.NET 4.5,每个Dispatcher.BeginInvoke/ InvokeAsync回调都是在它自己非常独特的同步上下文(一个实例DispatcherSynchronizationContext)上执行的.这种变化背后的原因是什么?
以下简单的WPF应用程序说明了这一点:
using System;
using System.Diagnostics;
using System.Threading;
using System.Windows;
using System.Windows.Threading;
namespace WpfApplication
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Action test = null;
var i = 0;
test = () =>
{
var sc = SynchronizationContext.Current;
Dispatcher.CurrentDispatcher.InvokeAsync(() =>
{
Debug.Print("same context #" + i + ": " +
(sc == SynchronizationContext.Current));
if ( i < 10 )
{
i++;
test();
}
});
};
this.Loaded += …Run Code Online (Sandbox Code Playgroud)