相关疑难解决方法(0)

为什么每个Dispatcher.BeginInvoke回调都有一个唯一的同步上下文?

我刚刚注意到,使用.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)

.net c# wpf multithreading synchronizationcontext

11
推荐指数
2
解决办法
1538
查看次数

标签 统计

.net ×1

c# ×1

multithreading ×1

synchronizationcontext ×1

wpf ×1