【发布时间】:2014-10-15 14:43:45
【问题描述】:
我有一个只运行一次代码的简单模式。它主要用于更新 UI 上的某些内容,而它可能会在后台经常更改。
private bool _updating;
private void UpdateSomething()
{
if (!_updating)
{
_updating = true;
Application.Current.Dispatcher.BeginInvoke(new Action(() =>
{
_updating = false;
DoSomething();
}), DispatcherPriority.Background);
}
}
我更愿意将样板代码放在一个简单的方法中:
public static void RunOnce(Action action, ref bool guard)
{
if (!guard)
{
guard = true;
Application.Current.Dispatcher.BeginInvoke(new Action(() =>
{
guard = false;
action();
}), DispatcherPriority.Background);
}
}
这样称呼它:
void UpdateSomething()
{
RunOnce(DoSomething, ref _updating);
}
但是,这不起作用,因为您不能在匿名方法中使用 ref 参数。 是否有任何解决方法,例如在方法执行时固定 ref 参数并释放它?
【问题讨论】:
-
你不能像这样
private static bool guard = false将 bool 保护声明为私有静态吗?还请查看此帖子,例如如何在匿名方法 stackoverflow.com/questions/23630765/… 中声明 ref 参数 -
将保护设为静态不是一种选择,因为我会单独更新多个实例。但是,将其放入链接线程中的引用类型将是一种选择。
标签: c# dispatcher ref