I haven't programmed thread access before on WinForms, but I have done it with PostSharp + Silverlight. So with a bit of googling, I'll give it a shot. No guarantees that it works though!
[Serializable]
public class OnGuiThreadAttribute : MethodInterceptionAspect
{
private static Control MainControl;
//or internal visibility if you prefer
public static void RegisterMainControl(Control mainControl)
{
MainControl = mainControl;
}
public override void OnInvoke(MethodInterceptionArgs eventArgs)
{
if (MainControl.InvokeRequired)
MainControl.BeginInvoke(eventArgs.Proceed);
else
eventArgs.Proceed();
}
}
And the idea is at the start of your application, register your main/root control with the attribute. Then any method you want to ensure runs on the main thread, just decorate with [OnGuiThread]
. If it's already on the main thread, it just runs the method. If it's not, it will promote the method call as a delegate to the main thread asynchronously.
EDIT: I just figured out (it's late) that you're asking to use the specific invoking method for the target control you're using. Assuming that you decorate instance methods on subclasses for your controls:
[Serializable]
public class OnGuiThreadAttribute : MethodInterceptionAspect
{
public override void OnInvoke(MethodInterceptionArgs eventArgs)
{
//you may want to change this line to more gracefully check
//if "Instance" is a Control
Control targetControl = (Control)eventArgs.Instance;
if (targetControl.InvokeRequired)
targetControl.BeginInvoke(eventArgs.Proceed);
else
eventArgs.Proceed();
}
}