问题委托语法在C# [英] Problem with delegate Syntax in C#

查看:95
本文介绍了问题委托语法在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我建了一个TESTBOX了解一些有关Windows应用程序的形式线程。
的Silverlight和Java所提供的调度,更新
GUI元素时,这确实有助于

I built a Testbox to learn something about threading in windows form applications. Silverlight and Java are providing the Dispatcher, which really helps when updating GUI Elements.

代码示例:
宣言类代表

Code Samples: Declaration Class Delegate

public delegate void d_SingleString(string newText);



创建线程

Create Thread

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

主题功能

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



委派文本框更新

Delegating TextBox Updates

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



有没有申报啦免费统计IN的BeginInvoke方法宣言的方式? !

Is there a way to declare the Declaration of the Delate IN the BeginInvoke Method?!

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



非常感谢,
rAyt

Many thanks, rAyt

推荐答案

在许多情况下,像这样的,最简单的方法是使用一种捕捉变量到线程之间传递状态;这意味着你可以保持局部的逻辑:

In many cases like this, the simplest approach is to use a "captured variable" to pass state between the threads; this means you can keep the logic localised:

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

如果我们的期望的它的上面是特别有用工作线程上被调用(这么少点检查 InvokeRequired ) - 注意,这是无论从UI或工作线程安全的,并允许我们通过尽可能多或尽可能线程之间小的状态。

The above is particularly useful if we expect it to be called on the worker thread (so little point checking InvokeRequired) - note that this is safe from either the UI or worker thread, and allows us to pass as much or as little state between the threads.

这篇关于问题委托语法在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆