BackgroundWorker - Cross-thread operation not valid

前端 未结 7 1064
南方客
南方客 2020-12-14 19:16

I have a winform application (one form), on this form there is a RichTextBox. In the constructor of this form I create an instance of the class MyClass. In the

7条回答
  •  有刺的猬
    2020-12-14 19:48

    To make it cleaner and based on Jon Skeet's suggestion, I made an extension method which does the same, you can change the "this Label control" to this TextBox control or simply use "this Control control" (and basically allow every control to be updated easily):

    internal static class ExtensionMethods
    {
        /// 
        /// Updates the label text while being used in a multithread app.
        /// 
        /// The control.
        /// The text.
        internal static void UpdateThreadedText(this Label control, string text)
        {
            Action action = () => control.Text = text;
            control.Invoke(action);
        }
    
        /// 
        /// Refreshes the threaded.
        /// 
        /// The control.
        internal static void RefreshThreaded(this Label control)
        {
            Action action = control.Refresh;
            control.Invoke(action);
        }
    }
    

    And then the usage is quite simple:

    this.yourLabelName.UpdateThreadedText("This is the text");
    this.yourTextBoxName.UpdateThreadedText("This is the text");
    this.yourControlName.UpdateThreadedText("This is the text");
    

    or

    this.yourLabelName.RefreshThreaded();
    

    Works for me nicely :)

提交回复
热议问题