Using WeakEventManager in Windows.Forms Application

When using the weak events described here http://wekempf.spaces.live.com/blog/cns!D18C3EC06EA971CF!373.entry in a Windows.Forms application, the WeakEventManager loses WeakReference objects. I think this is because without the message loop, WPF CleanupOperation is never executed, although ScheduleCleanup is called in WeakEventManager.ProtectedAddListener.

As a workaround, I implemented a cleanup function like this:

internal bool Cleanup()
{
    // The following is equivalent to 
    //    return this.Table.Purge(false);
    // but we need to use reflection to access the private members.

    PropertyInfo pi = typeof(WeakEventManager).GetProperty("Table", BindingFlags.Instance | BindingFlags.NonPublic);
    if (pi == null)
        return false;
    object table = pi.GetValue(this, null);
    MethodInfo mi = table.GetType().GetMethod("Purge", BindingFlags.Instance | BindingFlags.NonPublic);
    if (mi == null)
        return false;
    return (bool)mi.Invoke(table, new object[] { false });
}

      

and call it after each, for example. 16th challenge ProtectedAddListener

.

This works, but obviously I like to avoid this (ab) use of reflection.

So my questions are:

  • Is there a way to implement a cleanup function using public / protected members? WeakEventManager.Purge might be helpful, but I don't know how to use it.
  • Is there an easy way to start a WPF message loop in a Windows.Forms based application?
+2


source to share


1 answer


This code creates a static function that you can store in your cache. It will take away the pain of the reflection every time it is done and essentially does what you had. Cache it somewhere and invoke it every time in your weak event manager. Except for a single hit (during build / compile time), no further reflection occurs.



    using System.Windows;
    using System.Linq.Expressions;
    using Expression = System.Linq.Expressions.Expression;

    static void Main(string[] args)
    {
        Func<WeakEventManager, bool> cleanUpFunction = BuildCleanUpFunction();
    }

    private static Func<WeakEventManager, bool> BuildCleanUpFunction()
    {
        ParameterExpression managerParameter = Expression.Parameter(
            typeof(WeakEventManager),
            "manager"
        );
        return Expression.Lambda<Func<WeakEventManager, bool>>(
            Expression.Call(
                Expression.Property(
                    managerParameter,
                    "Table"
                ),
                "Purge",
                Type.EmptyTypes,
                Expression.Default(
                    typeof(bool)
                )
            ),
            managerParameter
        ).Compile();
    }

      

+2


source







All Articles