C#中的委托语法问题

Hen*_*sel 6 c# multithreading delegates

我构建了一个Testbox来了解Windows窗体应用程序中的线程.Silverlight和Java提供了Dispatcher,它在更新GUI元素时非常有用.

代码示例:声明类代表

public delegate void d_SingleString(string newText);
Run Code Online (Sandbox Code Playgroud)

创建线程

        _thread_active = true;
        Thread myThread = new Thread(delegate() { BackGroundThread(); });
        myThread.Start();
Run Code Online (Sandbox Code Playgroud)

线程功能

    private void BackGroundThread()
    {
        while (_thread_active)
        {
            MyCounter++;
            UpdateTestBox(MyCounter.ToString());
            Thread.Sleep(1000);
        }
    }
Run Code Online (Sandbox Code Playgroud)

委派TextBox更新

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

有没有办法在BeginInvoke方法中声明Delate宣言?!

就像是

BeginInvoke(*DELEGATE DECLARATION HERE*, new object[] { newText });
Run Code Online (Sandbox Code Playgroud)

非常感谢,rAyt

Mar*_*ell 9

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

public void UpdateTestBox(string newText)
{
    BeginInvoke((MethodInvoker) delegate {
        tb_output.Text = newText;
    });        
}
Run Code Online (Sandbox Code Playgroud)

如果我们期望在工作线程上调用它(这么少点检查InvokeRequired),上面特别有用- 注意这对UI或工作线程是安全的,并允许我们在线程之间传递尽可能多的状态.