开发者

Deriving from SynchonizationContext

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.

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/IEditableO开发者_开发百科bject, 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]);
}

}


Unfortunately you wrote something that already exists. The SynchronizationContext class does exactly what you do. Add a property to your main class, similar to this:

    public static SynchronizationContext SynchronizationContext {
        get {
            if (SynchronizationContext.Current == null) {
                SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
            }
            return SynchronizationContext.Current;
        }
    }

Or use AsyncOperationManager.SynchronizationContext, it does the exact same thing. Preferable of course.


I see nothing technically wrong with the code above..

However, it is more complicated than really necessary. There is no real reason to copy the ExecutionContext and run the operations within it. This happens automatically with a call to ThreadPool.QueueUserWorkItem. For details, see the docs of ExecutionContext:

Within an application domain, the entire execution context must be transferred whenever a thread is transferred. This situation occurs during transfers made by the Thread.Start method, most thread pool operations, and Windows Forms thread marshaling through the Windows message pump.

Personally, I would abandon tracking of the ExecutionContext unless there is a real need for it, and just simplify this to:

public class ImplicitSynchronisationContext : SynchronizationContext
{
    private readonly SynchronizationContext m_SyncContext;

    public ImplicitSynchronisationContext()
    {
        // Default to the current sync context if available.
        m_SyncContext = SynchronizationContext.Current;
    }


    public override void Post(SendOrPostCallback d, object state)
    {
        if (m_SyncContext != null)
        {
            m_SyncContext.Post(d, state);
        }
        else
        {
            ThreadPool.QueueUserWorkItem(_ => d(state));
        }
    }

    public override void Send(SendOrPostCallback d, object state)
    {
        if (m_SyncContext != null)
        {
            m_SyncContext.Send(d, state);
        }
        else
        {
            d(state);
        }
    }
}


I'm a little unsure about your motivation for writing this class.

If you're using WinForms or WPF, they provide implementations that are available using SynchronizationContext.Current.

If you're in a Console application, then you control the main thread. How are you communicating with this thread?

If you're running a windows message loop, presumably you are using WinForms or WPF.

If you're waiting on a producer/consumer queue, your main thread will be the one consuming the events, so by definition you will be on the main thread.

Nick


Thanks very much for the feedback everyone.

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

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.

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.

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!

Cheers!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜