System.Timers.Timer.SynchronizingObject ManagedThreadId不是来自主线程

时间:2017-09-07 09:29:13

标签: c# wpf multithreading entity-framework timer

我正在使用Entity Framework开发WPF应用程序(MVVM)。我想在给定的时间间隔内查询SQL服务器上的表,以向用户显示更新的DB值。为此,我在我的ViewModel中设置了一个计时器,如下所示:

RefreshTimer = new System.Timers.Timer(2000.0);
RefreshTimer.Enabled = true;
RefreshTimer.SynchronizingObject = new Synchronizer();
RefreshTimer.Elapsed += RefreshTimer_Elapsed;

其中Synchronizer是ISynchronizeInvoke的实现:

internal class Synchronizer : ISynchronizeInvoke
{
    private object _sync = new object();

    public bool InvokeRequired { get { return true; } }

    public IAsyncResult BeginInvoke(Delegate method, object[] args)
    {
        var result = new SimpleAsyncResult();

        ThreadPool.QueueUserWorkItem(delegate {
            result.AsyncWaitHandle = new ManualResetEvent(false);
            try
            {
                result.AsyncState = Invoke(method, args);
            }
            catch (Exception exception)
            {
                result.Exception = exception;
            }
            result.IsCompleted = true;
        });

        return result;
    }

    public object EndInvoke(IAsyncResult result)
    {
        if (!result.IsCompleted)
        {
            result.AsyncWaitHandle.WaitOne();
        }

        return result.AsyncState;
    }

    public object Invoke(Delegate method, object[] args)
    {
        lock (_sync)
        {
            return method.DynamicInvoke(args);
        }
    }
}

internal class SimpleAsyncResult : IAsyncResult
{
    object _state;

    public bool IsCompleted { get; set; }

    public WaitHandle AsyncWaitHandle { get; internal set; }

    public object AsyncState
    {
        get
        {
            if (Exception != null)
            {
                throw Exception;
            }
            return _state;
        }
        internal set
        {
            _state = value;
        }
    }

    public bool CompletedSynchronously { get { return IsCompleted; } }

    internal Exception Exception { get; set; }
}

如果我理解正确,SynchronizingObject应该在创建SynchronizingObject的线程上封送Elapsed事件。在我的情况下,这是主线程。现在考虑以下代码来处理事件:

private void RefreshTimer_Elapsed(object sender, ElapsedEventArgs e)
{
    System.Diagnostics.Debug.WriteLine($"RefreshTimer ManagedThreadID: {Thread.CurrentThread.ManagedThreadId}");
    RefreshTimer.SynchronizingObject.Invoke((Action)(() => { TestMethod(); }), null);
}

public void TestMethod()
{
    System.Diagnostics.Debug.WriteLine($"TestMethod ManagedThreadID: {Thread.CurrentThread.ManagedThreadId}");
}

TestMethod是我更新/重新加载我的Entity对象的地方,因此View会自动显示最新数据。当我尝试这样做时,我得到一个InvalidOperationException,指出调用线程无法访问此对象,因为另一个线程拥有它

输出结果为:

RefreshTimer ManagedThreadID: 5
TestMethod ManagedThreadID: 5
RefreshTimer ManagedThreadID: 4
TestMethod ManagedThreadID: 4
RefreshTimer ManagedThreadID: 8
TestMethod ManagedThreadID: 8

我怀疑这是我得到上述异常的原因。我希望输出为:

RefreshTimer ManagedThreadID: 5
TestMethod ManagedThreadID: 1
RefreshTimer ManagedThreadID: 4
TestMethod ManagedThreadID: 1
RefreshTimer ManagedThreadID: 8
TestMethod ManagedThreadID: 1

有谁能告诉我我做错了什么以及如何让SynizingObject.Invoke方法在主线程上执行?

1 个答案:

答案 0 :(得分:3)

您可以使用调度程序安排在调度程序线程上执行委托:

private void RefreshTimer_Elapsed(object sender, ElapsedEventArgs e)
{
    System.Diagnostics.Debug.WriteLine($"RefreshTimer ManagedThreadID: {Thread.CurrentThread.ManagedThreadId}");
    Application.Current.Dispatcher.Invoke(new Action(() => { TestMethod(); }))
}

您可能还想阅读此内容:https://www.thomasclaudiushuber.com/2017/02/15/how-to-test-code-that-uses-singletons-like-application-current-dispatcher/