C# 如何编写PostSharp调用特性以简化跨线程控件更新
当我想跨线程更新控件时,我通常会这样做:C# 如何编写PostSharp调用特性以简化跨线程控件更新,c#,winforms,postsharp,multithreading,C#,Winforms,Postsharp,Multithreading,当我想跨线程更新控件时,我通常会这样做: this.Invoke((MethodInvoker)delegate { SomeProcedure(); }); 建议的方法实际上是为要更新的特定控件调用调用程序,但99%的时间表单(即我的示例中的“this”)和控件都是在同一线程上创建的,因此为了简单起见,我非常喜欢这样做 我在想,如果我能在某个程序上加上一个后锐利的方面,那就太好了,这会给我带来混乱的陈述 然后去。。。(哦,是的,第一个可用答案加100分:)我以前没有在WinForms上编程线
this.Invoke((MethodInvoker)delegate { SomeProcedure(); });
建议的方法实际上是为要更新的特定控件调用调用程序,但99%的时间表单(即我的示例中的“this”)和控件都是在同一线程上创建的,因此为了简单起见,我非常喜欢这样做
我在想,如果我能在某个程序上加上一个后锐利的方面,那就太好了,这会给我带来混乱的陈述
然后去。。。(哦,是的,第一个可用答案加100分:)我以前没有在WinForms上编程线程访问,但我已经用PostSharp+Silverlight完成了。所以用谷歌搜索一下,我会试试看。但不能保证它能工作
[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();
}
}
这个想法是在应用程序开始时,用属性注册主/根控件。然后,任何要确保在主线程上运行的方法,只需使用[OnGuiThread]
进行修饰即可。如果它已经在主线程上,它只运行该方法。如果不是,它将把方法调用作为委托异步升级到主线程
编辑:我刚刚发现(已经晚了),您要求对正在使用的目标控件使用特定的调用方法。假设您在控件的子类上修饰实例方法:
[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();
}
}
我不能完全确定我是否完全理解你想要什么,特别是关于你的第二段。但是PostSharp的示例代码有帮助吗?