繁体   English   中英

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

[英]C# thread-safe calls on dynamically created controls

我知道如何在用户控件上执行线程安全的调用,但是当它们动态生成时,我没有任何线索。 我试图列出它们的数组列表(富文本框),然后我遇到了“参数启动线程”委托的问题。 您的输入非常感谢。

    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控件是不安全的。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM