I want to log in to RichTextBox, but during long operations the form hangs.
I tried to call in a separate task, but an error occurs that accessing the RichTextBox from another thread is not possible.
How to get out of this situation?
I want to log in to RichTextBox, but during long operations the form hangs.
I tried to call in a separate task, but an error occurs that accessing the RichTextBox from another thread is not possible.
How to get out of this situation?
Elements UI do not like to work with other threads, and should not. Therefore, you must either use ready-made components to implement inter-thread communication, or implement it explicitly.
I do not see a deep sense in copying official documentation on ready-made components, see the code examples by reference. All references are on MSDN.
1. Native WinForms Solution - use the BackgroundWorker
component: description , examples , tutorial
2. You can also use Dispatcher , even though it belongs to WPF. Description .
The choice of option is in my opinion a matter of taste, but I have not very practical experience in this, I may be mistaken.
3. BeginInvoke is another option for accessing methods between threads. The code will look like this:
using System; using System.Threading; using System.Windows.Forms; public partial class Form1 : Form { public Form1() { InitializeComponent(); Task.Run(new Action(TestThreading)); AddText("Same thread"); } void TestThreading() { Thread.Sleep(2000); AddText("Async change"); } public void AddText(string text) { if (this.textBox1.InvokeRequired) { Action<string> updaterdelegate = new Action<string>(AddText); try { this.Invoke(updaterdelegate, new object[] { text }); } catch (ObjectDisposedException ex) { } } else { textBox1.Text = text; } } }
an idea from here , but there is an error that I have already corrected, you can copy-paste, not forgetting to throw on the TextBox
form, it will also work with any other UI elements and any of their properties. But if there are a lot of threads, do not forget to place locks on the record.
Source: https://ru.stackoverflow.com/questions/547493/
All Articles