views:

51

answers:

4

Hi,

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/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]);
}

}

+1  A: 

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);
        }
    }
}
Reed Copsey
Thanks, but this doesn't actually solve my problem. Even if m_SyncContext is null in the Post method I want the async invocation to be executed on the thread that created my class - in your case you just fire it off to the thread pool. Or am I missing something here?
@user477161: Your code did that, as well. The only way to "fire off a method in the thread that constructed this" would be to provide some form of message loop that could handle the marshaling. Remember, a thread is always running (unless explicitly blocked), so unless you provide some means of polling for operations in that thread, there's no way to just push a method onto the calling thread. I've written custom SynchronizationContext implementations that handle polling for this, but it requires implementing your own message pump or polling of some form.
Reed Copsey
A: 

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

Nick Butler
I tend to agree. I was testing this in a ConsoleApp in which SynchronizationContext.Current is null - which confirmed what I had read elsewhere, that it isn't guaranteed to be set. However, like you say, in WinForms and WPF this propery is set (at least after a form or control has been created) so isn't really an issue there.
+2  A: 

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.

Hans Passant
I avoided this because I read somewhere that this can cause unexpected behaviour. I.e. if you initialise this property before a WinForms app sets the SynchronizationContext, will it then use the one already created or create a new one? I'll need to do some more testing. I'll have a look at AsyncOperationManager as well, thanks. Could you perhaps expand on why it is preferrable to use?
It is preferable because it is already there. The exact same unexpected behavior will occur with your code as well when the winforms programmer calls your code *before* calling Application.Run().
Hans Passant
After a bit more digging I beg to differ. Yes, the SynchronizationContext of the UI thread is set when calling Application.Run(), but so is AsyncOperationManager.SynchonizationContext (in a WinForms app at least). I.e. the AsyncOperationManager.SynchronizationContext is set to WindowsSynchronizationContext in Application.Run() so using it rather than SynchronizationContext.Current doesn't actually solve the problem. However, I don't really see a need for initialising/using the SynchronizationContext before Application.Run() so in most cases this is a non-issue. Thanks for the feedback.
Or perhaps I misunderstood you? In any case, I agree that my implementation doesn't solve the problem you're referring to.
AsyncOperationManager.SynchronizationContext ensures that you always get a non-null synchronizer. It returns the winforms synchronizer in a winforms app (after Application.Run was called), the default synchronizer in a console mode app.
Hans Passant
Just came to the same conclusion, thanks very much for your feedback. Just to add to that, the same applies for a WPF application as would seem to be implied by your answer and as I've just verified.
Yup, it is the way to go. Please close your question by marking the answer.
Hans Passant
A: 

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!