gpt4 book ai didi

c# - 如何编写 PostSharp Invoke 方面来简化跨线程控制更新

转载 作者:行者123 更新时间:2023-11-30 14:00:20 26 4
gpt4 key购买 nike

当我想跨线程更新控件时,我通常会这样做:

this.Invoke((MethodInvoker)delegate { SomeProcedure(); });

建议的方法实际上是为您要更新的特定控件调用调用程序,但 99% 的时间表单(即我的示例中的“this”)和控件将被创建在同一个线程上,所以为了简单起见,我真的很喜欢这样做。

我当时在想,如果我只是在 SomeProcedure 之上放置一个 PostSharp 方面,这会为我把它包装在一堆乱七八糟的声明中,那就太好了。

然后开始...(哦,是的,第一个可用答案可获得 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] 装饰。如果它已经在主线程上,它只是运行该方法。如果不是,它将以异步方式将方法调用提升为对主线程的委托(delegate)。

编辑:我刚刚发现(已经晚了)您要求对您正在使用的目标控件使用特定的调用方法。假设您在控件的子类上装饰实例方法:

[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();
}
}

关于c# - 如何编写 PostSharp Invoke 方面来简化跨线程控制更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11183026/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com