-2

I was trying to implement an aspect following a WPF example, but I can't figure out how to make it work for WinForms.

class RunOnUIThreadAttribute : IMethodInterceptionAspect
{
    public override void OnInvoke(MethodInterceptionArgs args)
    {
        DispatcherObject dispatchedObj = (DispatcherObject)args.Instance;
        if (dispatchedObj.CheckAccess())
        {
            args.Proceed();
        }
        else
        {
            dispatchedObj.Dispatcher.Invoke((Action)(() => args.Proceed()));
        }
    }
}

How do I get the equivalent of Dispatcher working on Windows Forms?

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
user1012732
  • 181
  • 2
  • 14
  • 1
    Do you know how to switch to the UI thread in Windows Forms outside of an aspect? – nvoigt Jun 03 '15 at 07:42
  • Helpful SO links: http://stackoverflow.com/questions/4928195/c-sharp-windows-forms-application-updating-gui-from-another-thread-and-class and http://stackoverflow.com/questions/661561/how-to-update-the-gui-from-another-thread-in-c – seveves Jun 03 '15 at 07:48

1 Answers1

2

If args.Instance is a Control, you could use InvokeRequired and Invoke, instead of their WPF counterparts:

class RunOnUIThreadAttribute : IMethodInterceptionAspect
{
    public override void OnInvoke(MethodInterceptionArgs args)
    {
        Control c = (Control)args.Instance;
        if (!c.InvokeRequired)
        {
            args.Proceed();
        }
        else
        {
            c.Invoke((Action)(() => args.Proceed()));
        }
    }
}
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325