Wednesday, April 21, 2010

Hosting OpenSpan: A complete ISynchronizeInvoke wrapper for the Dispatcher

As I mentioned in my last post, I've been working on a sample where I host OpenSpan adapters inside of a WPF Prism application. Here's a screenshot that will help give you a sense of it.


When I started fleshing out the sample, I realized that WPF didn't provide an object that implemented ISynchronizeInvoke that I could pass to the adapter Start method. As a little background, we added an overload to the Start method that takes an instance of ISynchronizeInvoke as a convenience for developers using adapters within windows forms applications. Normally, within the OpenSpan runtime, adapters fire asynchronous events on thread pool threads. Our automation surface abstracts the invocations required to interact with windows forms from visual developers.

When hosting adapters directly in .NET, we quickly realized that it was painful to force developers to invoke onto the windows forms thread anytime they needed to update their UI within an adapter event. Thus, we added an overload to the Start method where developers could pass in an instance of ISynchronizeInvoke. In practice, since all windows forms controls implement ISynchronizeInvoke, developers simply pass in their form or user control. When an adapter is started with an instance of ISynchronizeInvoke, it will automatically invoke all events onto the right thread.

However, the WPF Dispatcher object, which provides equivalent functionality to ISynchronizeInvoke, does not actually implement ISynchronizeInvoke. A quick search revealed that other folks had run into the same issue with WPF and created wrappers. However, looking over the wrappers, they weren't entirely complete. It seems that nobody had implemented every method or property required. In particular I knew that our adapters depended on the EndInvoke method and the IAsyncResult.AsyncWaitHandle property.

To remedy this, I implemented my own wrapper. In addition to the public DispatchWrapper, I created a couple of nested private classes, DispatchOperationWrapper and DispatcherOperationWaitHandle, to hide the IAsyncResult and WaitHandle implementation details. Unlike some of the samples I found the implementation below doesn't use any looping or sleeps to wait. Also note that the implementation for IAsyncResult.CompletedSynchronously always return false. This conforms to the IAsyncResult guidance on MSDN.


using System;
using System.Threading;
using System.Windows.Threading;

namespace OpenSpan.Samples
{
public class DispatcherWrapper : ISynchronizeInvoke
{
private Dispatcher _Dispatcher;

public DispatcherWrapper(Dispatcher dispatcher)
{
_Dispatcher = dispatcher;
}

#region ISynchronizeInvoke Members
public IAsyncResult BeginInvoke(Delegate method, object[] args)
{
DispatcherOperation op = _Dispatcher.BeginInvoke(method, args);
return new DispatcherOperationWrapper(op);
}

public object EndInvoke(IAsyncResult result)
{
DispatcherOperationWrapper wrapper = result as DispatcherOperationWrapper;
if (wrapper != null)
{
wrapper.Operation.Wait();
return wrapper.Operation.Result;
}
throw new ArgumentException("Result does not wrap a DispatchOperation");
}

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

public bool InvokeRequired
{
get { return _Dispatcher.CheckAccess(); }
}

#endregion

private class DispatcherOperationWrapper : IAsyncResult
{
private DispatcherOperationWaitHandle _WaitHandle;
private DispatcherOperation _Operation;
private object _State;

public DispatcherOperationWrapper(DispatcherOperation operation)
{
_Operation = operation;
}

public DispatcherOperationWrapper(DispatcherOperation operation, object state)
: this(operation)
{
_State = state;
}

public DispatcherOperation Operation
{
get
{
return _Operation;
}
}

#region IAsyncResult Members
public object AsyncState
{
get { return _State; }
}

public WaitHandle AsyncWaitHandle
{
get
{
if (_WaitHandle == null)
{
_WaitHandle = new DispatcherOperationWaitHandle(_Operation);
}
return _WaitHandle;
}
}

public bool CompletedSynchronously
{
get { return false; }
}

public bool IsCompleted
{
get { return (_Operation.Status == DispatcherOperationStatus.Completed); }
}
#endregion

private class DispatcherOperationWaitHandle : WaitHandle
{
private DispatcherOperation _Operation;

public DispatcherOperationWaitHandle(DispatcherOperation operation)
{
_Operation = operation;
}

public override bool WaitOne()
{
DispatcherOperationStatus status = _Operation.Wait();
return (status == DispatcherOperationStatus.Completed);
}

public override bool WaitOne(int milliseconds)
{
return this.WaitOne(new TimeSpan(0, 0, 0, 0, milliseconds));
}

public override bool WaitOne(int milliseconds, bool exitContext)
{
return WaitOne(milliseconds);
}

public override bool WaitOne(TimeSpan timeout)
{
DispatcherOperationStatus status = _Operation.Wait(timeout);
return (status == DispatcherOperationStatus.Completed);
}

public override bool WaitOne(TimeSpan timeout, bool exitContext)
{
return this.WaitOne(timeout);
}
}
}
}
}

1 comments:

alantan said...

Yet another great and elegant solution, Damon. I'm now using it in our project.

Just one comment - I noticed a small error due to InvokeRequired being the opposite of CheckAccess. I've added a '!' before the return:

public bool InvokeRequired
{
get { !return _Dispatcher.CheckAccess(); }
}

Alan