C#中的委托语法问题

2

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

问题描述

我构建了一个测试箱来了解有关 Windows 窗体应用程序中的线程的知识.Silverlight 和 Java 正在提供 Dispatcher,这在更新时确实很有帮助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.

代码示例:声明类委托

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 方法中声明延迟声明?!

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

类似

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

非常感谢,雷特

推荐答案

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

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#中的委托语法问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

C# 中的多播委托奇怪行为?
Multicast delegate weird behavior in C#?(C# 中的多播委托奇怪行为?)...
2023-11-11 C#/.NET开发问题
6

参数计数与调用不匹配?
Parameter count mismatch with Invoke?(参数计数与调用不匹配?)...
2023-11-11 C#/.NET开发问题
26

如何将代表存储在列表中
How to store delegates in a List(如何将代表存储在列表中)...
2023-11-11 C#/.NET开发问题
6

代表如何工作(在后台)?
How delegates work (in the background)?(代表如何工作(在后台)?)...
2023-11-11 C#/.NET开发问题
5

没有 EndInvoke 的 C# 异步调用?
C# Asynchronous call without EndInvoke?(没有 EndInvoke 的 C# 异步调用?)...
2023-11-11 C#/.NET开发问题
2

Delegate.CreateDelegate() 和泛型:错误绑定到目标方法
Delegate.CreateDelegate() and generics: Error binding to target method(Delegate.CreateDelegate() 和泛型:错误绑定到目标方法)...
2023-11-11 C#/.NET开发问题
14