C# 线程安全调用动态创建的控件

标签 c# multithreading user-controls delegates thread-safety

我知道如何对用户控件执行线程安全调用,但是当它们是动态生成时我却一无所知。我试图制作它们的数组列表(富文本框),之后我遇到了“参数启动线程”委托(delegate)的问题。非常感谢您的输入。

    private void SetText(string text)
    {
        // InvokeRequired required compares the thread ID of the 
        // calling thread to the thread ID of the creating thread. 
        // If these threads are different, it returns true. 
        if (this.currentBox.InvokeRequired)
        {
            SetTextCallback d = new SetTextCallback(SetText);
            this.Invoke( d, new object[] { text } );
        }
        else
        {
            this.currentBox.Text += text;
        }
    }

  // This method is executed on the worker thread and makes 
    // a thread-safe call on the TextBox control. On a specific text box.....
    private void ThreadProcSafe()
    {
        int i = 0;
        while(_stop_threads == false) {
            this.SetText(String.Format("{0}\n", i));

            ++i;
            Thread.Sleep(100);
        }

        this.SetText(String.Format("Thread Time: {0}:{1}:{2}\n", DateTime.Now.TimeOfDay.Hours, DateTime.Now.TimeOfDay.Minutes, DateTime.Now.TimeOfDay.Seconds)); 

    }

最佳答案

问题是,虽然每个 UI 控件都有一个单独的线程,但 Windows 窗体在单个线程下工作。因此,从单独的线程更新 UI 控件是不安全的。

也许您可以从这些线程中填充字典或数组,并在表单的单线程下更新该数组的结果。这样,您将从更新的值数组同时更新所有 UI 控件。它是线程安全的,并且消耗更少的系统资源。

关于C# 线程安全调用动态创建的控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12766219/

相关文章:

c# - 如何通过 XAML 中定义的数据模板以编程方式创建元素?

c# - LINQ:将 object[] 转换为 int?[]

iOS错误: Thread 1:EXC_BAD_ACCESS(code=1,地址=0x726f635f)?

python - 为什么线程 ID 变得这么大

silverlight - 从 UserControl 抽象子类继承

c# - 在启动线程之前无法更改 WPF 控件状态

c# - ASP.NET C# 使用列表导航如何在事件导航页面上设置 id ="current"?

Java:从另一个线程停止一个线程中的所有 Activity

c# - 用户控件 - 自定义属性

c# - 如何使用户控件的背景透明?