【问题标题】:Dispatcher.BeginInvoke Action with ParametersDispatcher.BeginInvoke 带参数的操作
【发布时间】:2011-07-28 14:06:23
【问题描述】:

在处理一些调整大小之前,我正在使用 Dispatcher 更新我的 UI。 问题在于 BeginInvoke(DispatcherPriorty, new ACTION) 的部分是我卡住的地方。 我想调用带有参数的方法,我不知道为什么。

那是我目前的调度员:

void s_SizeChanged(object sender, SizeChangedEventArgs e)
{
    Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, new Action(test));

}

这是我正在调用的方法:

public void test()
{
    foreach (Structures s in ((TreeView)this.cont.Children[0]).Items)
        s.updateRelationLines(this.Data, this.cont.ColumnDefinitions[1]);
}

我只想用参数替换this.Datathis.cont.Columndefinitions[1]

【问题讨论】:

  • 您希望参数的值如何设置?

标签: c# dispatcher


【解决方案1】:

您可以为此使用 lambda 表达式:

Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, 
    new Action(() => test(param1, param2)));

这基本上创建了一个匿名方法

void myMethod() {
    test(param1, param2);
}

并通过调度程序调用此方法。一些编译器魔法确保 param1 和 param2 可用于此方法,即使它们仅在您的 s_SizeChanged 方法的范围内。可以在此处找到更多详细信息:

【讨论】:

  • 使用这种方法需要注意的一点是,如果在调用 test 之前更改了 param1 或 param2,那么 test 将获得 param1/param2 的新值而不是旧值。
  • @CodeNaked,该错误已在 C# 5 中修复。
  • @l33t:您可能是指foreach 问题。总的来说,CodeNaked 的声明仍然成立:param1 = 1; BeginInvoke(...); param1 = 2 可能仍然使用 param1 的新值。
  • 我一直在寻找一种在进程运行时禁用按钮的简单方法。我发现的只是令人费解和荒谬的答案。这太完美了!
【解决方案2】:

你应该可以做到:

Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, new Action<Type1, Type2>(test), type1, type2);

使用如下回调:

public void test(Type1 type1, Type2 type2) {
        foreach (Structures s in ((TreeView)this.cont.Children[0]).Items)
            s.updateRelationLines(type1, type2);
    }

【讨论】:

    猜你喜欢
    • 2013-09-21
    • 1970-01-01
    • 1970-01-01
    • 2015-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-17
    相关资源
    最近更新 更多