【问题标题】:Problem with delegate Syntax in C#C#中的委托语法问题
【发布时间】:2009-05-25 09:32:05
【问题描述】:

我构建了一个测试箱来学习有关 Windows 窗体应用程序中的线程的知识。 Silverlight 和 Java 提供了 Dispatcher,这在更新时确实很有帮助 GUI 元素。

代码示例: 声明类委托

public delegate void d_SingleString(string newText);

创建线程

        _thread_active = true;
        Thread myThread = new Thread(delegate() { BackGroundThread(); });
        myThread.Start();

线程函数

    private void BackGroundThread()
    {
        while (_thread_active)
        {
            MyCounter++;
            UpdateTestBox(MyCounter.ToString());
            Thread.Sleep(1000);
        }
    }

委派文本框更新

    public void UpdateTestBox(string newText)
    {
        if (InvokeRequired)
        {
            BeginInvoke(new d_SingleString(UpdateTestBox), new object[] { newText });
            return;
        }
        tb_output.Text = newText;
    }

有没有办法在 BeginInvoke 方法中声明延迟声明?!

类似

BeginInvoke(*DELEGATE DECLARATION HERE*, new object[] { newText });

非常感谢, 雷特

【问题讨论】:

    标签: c# multithreading delegates


    【解决方案1】:

    在很多这样的情况下,最简单的方法是使用“捕获的变量”在线程之间传递状态;这意味着您可以保持逻辑本地化:

    public void UpdateTestBox(string newText)
    {
        BeginInvoke((MethodInvoker) delegate {
            tb_output.Text = newText;
        });        
    }
    

    如果我们期望在工作线程上调用上面的内容特别有用(检查InvokeRequired 的意义不大) - 请注意,这对于 UI 或工作线程都是安全的,并且允许我们在线程之间传递尽可能多的状态。

    【讨论】:

    • 爱你的 eloboration 马克。刚刚学到了比阅读 MSDN 10 分钟更多的东西:)
    • 非常优雅的解决方案;这应该是这个问题的公认答案。
    • @Spence - 这与 STA/MTA 无关;完全没有。
    • 对不起弗雷德里克。那看起来好多了;)
    • 没问题 rAyt;虽然我们都是代表迷,但我们也必须谦虚并促进更好的解决方案;)
    【解决方案2】:

    对于像这样的简单委托,您可以使用框架中的 Action<T> 委托 (link to msdn)。

    public void UpdateTestBox(string newText)
    {
        if (InvokeRequired)
        {
            BeginInvoke(new Action<string>(UpdateTestBox), new object[] { newText });
            return;
        }
        tb_output.Text = newText;
    }
    

    这样您就不需要维护自己的委托声明。

    【讨论】:

      猜你喜欢
      • 2010-12-12
      • 2011-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-12
      相关资源
      最近更新 更多