从SynchonizationContext派生SynchonizationContext

2023-09-05 02:04:58 作者:乱一世狂傲

总之,我实现了从的SynchronizationContext派生,以方便为GUI应用程序,以提高消费对线程不是GUI线程的其它事件类。我将十分AP preciate意见对我实施。具体来说,就是你有什么建议对或可能会导致我没有预见到的问题?我的初步测试已经成功。

In short, I've implemented a class that derives from SynchronizationContext to make it easy for GUI applications to consume events raised on threads other than the GUI thread. I'd very much appreciate comments on my implementation. Specifically, is there anything you would recommend against or that might cause problems that I haven't foreseen? My initial tests have been successful.

长版本: 我目前正在开发一个分布式系统(WCF),使用回调传播从服务器到客户端事件的业务层。我的一个设计目标是提供可绑定的业务对象(即INotifyPropertyChanged的/ IEditableObject等)可以很容易地在客户端消费这些。作为其中的一部分我提供一个处理事件,因为他们来了回调接口的实现,更新,反过来,提高性能改变事件的业务对象。因此,我需要这些事件进行GUI线程上的提高(以避免跨线程操作例外)。因此,我试图提供一种定制的SynchronizationContext,用于由类实现回调接口传播事件到GUI线程。另外,我想这个实现独立于客户端的环境 - 例如一个WinForms GUI应用程序或ConsoleApp或别的东西。换句话说,我不想假设静态SynchronizationContext.Current可用。因此,我使用的ExecutionContext作为后备策略。

The long version: I'm currently developing the business layer of a distributed system (WCF) that uses callbacks to propagate events from the server to clients. One of my design objectives is to provide bindable business objects (i.e. INotifyPropertyChanged/IEditableObject, etc.) to make it easy to consume these on the client-side. As part of this I provide an implementation of the callback interface that handles events as they come in, updates the business objects which, in turn, raise property changed events. I therefore need these events to be raised on the GUI thread (to avoid cross-thread operation exceptions). Hence my attempt at providing a custom SynchronizationContext, which is used by the class implementing the callback interface to propagate events to the GUI thread. In addition, I want this implementation to be independent of the client environment - e.g. a WinForms GUI app or a ConsoleApp or something else. In other words, I don't want to assume that the static SynchronizationContext.Current is available. Hence my use of the ExecutionContext as a fallback strategy.

public class ImplicitSynchronisationContext : SynchronizationContext

{

private readonly ExecutionContext m_ExecContext;
private readonly SynchronizationContext m_SyncContext;


public ImplicitSynchronisationContext()
{
    // Default to the current sync context if available.
    if (SynchronizationContext.Current != null)
    {
        m_SyncContext = SynchronizationContext.Current;
    }
    else
    {
        m_ExecContext = ExecutionContext.Capture();
    }
}


public override void Post(SendOrPostCallback d, object state)
{
    if (m_SyncContext != null)
    {
        m_SyncContext.Post(d, state);
    }
    else
    {
        ExecutionContext.Run(
            m_ExecContext.CreateCopy(),
            (object args) =>
            {
                ThreadPool.QueueUserWorkItem(new WaitCallback(this.Invoker), args);
            },
            new object[] { d, state });
    }
}
public override void Send(SendOrPostCallback d, object state)
{
    if (m_SyncContext != null)
    {
        m_SyncContext.Send(d, state);
    }
    else
    {
        ExecutionContext.Run(
            m_ExecContext.CreateCopy(),
            new ContextCallback(this.Invoker),
            new object[] { d, state });
    }
}


private void Invoker(object args)
{
    Debug.Assert(args != null);
    Debug.Assert(args is object[]);

    object[] parts = (object[])args;

    Debug.Assert(parts.Length == 2);
    Debug.Assert(parts[0] is SendOrPostCallback);

    SendOrPostCallback d = (parts[0] as SendOrPostCallback);

    d(parts[1]);
}

}

推荐答案

非常感谢您的回馈大家。

Thanks very much for the feedback everyone.

汉斯帕桑特的回答使我演进/更改我的解决方案。

Hans Passant's answer led me to evolve/change my solution.

只是为了回顾一下,我的问题本质上是如何从我的WCF服务异步回调传播到客户端(的WinForms或WPF)的UI线程,而无需在客户端开发方面的任何工作。

Just to recap, my problem was essentially how to get async callbacks from my WCF service to propagate to the UI thread of a client (WinForms or WPF) without requiring any work on the part of the client developer.

我给了上面,因为它是多余的提供的实施。我的服务实现回调合同,现在只是有一个重载的构造函数布尔synchroniseCallbacks。如果这是真的,我存储的引用,AsyncOperationManager.SynchronizationContext。当事件都从我的服务我发布或使用该同步情况下发送。

I've dropped the implementation offered above because it is redundant. My implementation of the service callback contract now simply has an overloaded constructor that takes bool synchroniseCallbacks. When it is true I store a reference to AsyncOperationManager.SynchronizationContext. When events come in from my service I post or send them using that sync context.

正如汉斯指出,如果使用同步上下文由AsyncOperationManager公开的好处是,它永远不会为空并且,此外,在GUI应用程序,如WinForms和WPF它会返回UI线程的同步方面 - 问题解决了!

As Hans pointed out, the benefit if using the sync context exposed by AsyncOperationManager is that it will never be null and, also, in GUI apps such as WinForms and WPF it will return the sync context of the UI thread - problem solved!

干杯!

相关推荐