I would like to create a dynamic proxy for binding WinForms controls to objects changed by a different (non-GUI) thread. Such a proxy would intercept the PropertyChanged event and dispatch it using the proper SynchronizationContext.
That way I could use a helper class to do the job, without having to implement the synchronization manually every time (if (control.InvokeRequired) etc.
).
Is there a way to do that using LinFu, Castle or a similar library?
[Edit]
Data source is not necessarily a list. It can be any business object, e.g.:
interface IConnection : INotifyPropertyChanged
{
ConnectionStatus Status { get; }
}
I could create a wrapper which could do the job, and it would look something like this:
public class ConnectionWrapper : IConnection
{
private readonly SynchronizationContext _ctx;
private readonly IConnection _actual;
public ConnectionWrapper(IConnection actual)
{
_ctx = SynchronizationContext.Current;
_actual= actual;
_actual.PropertyChanged +=
new PropertyChangedEventHandler(actual_PropertyChanged);
}
// we have to do 2 things:
// 1. wrap each property manually
// 2. handle the source event and fire it on the GUI thread
private void PropertyChanged(object sender, PropertyChangedEvArgs e)
{
// we will send the same event args to the GUI thread
_ctx.Send(delegate { this.PropertyChanged(sender, e); }, null);
}
public ConnectionStatus Status
{ get { return _instance.Status; } }
public event PropertyChangedEventHandler PropertyChanged;
}
(there may be some errors in this code, I am making it up)
What I would like to do is to have a dynamic proxy (Reflection.Emit) one liner for this, e.g.
IConnection syncConnection
= new SyncPropertyChangedProxy<IConnection>(actualConnection);
and I wanted to know if something like this was possible using existing dynamic proxy implementations.
A more general question would be: How to intercept an event when creating a dynamic proxy? Intercepting (overriding) properties is explained well in all implementations.
[Edit2]
The reason (I think) I need a proxy is that the stack trace looks like this:
at PropertyManager.OnCurrentChanged(System.EventArgs e) at BindToObject.PropValueChanged(object sender, EventArgs e) at PropertyDescriptor.OnValueChanged(object component, EventArgs e) at ReflectPropertyDescriptor.OnValueChanged(object component, EventArgs e) at ReflectPropertyDescriptor.OnINotifyPropertyChanged(object component, PropertyChangedEventArgs e) at MyObject.OnPropertyChanged(string propertyName)
You can see that BindToObject.PropValueChanged
does not pass the sender
instance to the PropertyManager
, and Reflector shows that sender object is not referenced anywhere. In other words, when the PropertyChanged
event is triggered, component will use reflection to access the property of the original (bound) data source.
If I wrapped my object in a class containing only the event (as Sam proposed), such wrapper class would not contain any properties which could be accessed through Reflection.