The problem is here:
this.richTextBox1.LoadFile(path, RichTextBoxStreamType.RichText);
this.richTextBox1.ReadOnly = true;
These two lines should be in a method invoked via
System.Windows.Forms.Control.Invoke
.
You cannot call anything related to UI from non-UI thread. Instead, you need to use the method
Invoke
or
BeginInvoke
of
System.Windows.Threading.Dispatcher
(for both Forms or WPF) or
System.Windows.Forms.Control
(Forms only).
You will find detailed explanation of how it works and code samples in my past answers:
Control.Invoke() vs. Control.BeginInvoke()[
^],
Problem with Treeview Scanner And MD5[
^].
See also more references on threading:
How to get a keydown event to operate on a different thread in vb.net[
^],
Control events not firing after enable disable + multithreading[
^].
Also, previous two lines make no sense. Your invoked method does nothing, and you read the content of the file stream to memory stream, which makes no sense. You really need a string to be assigned to the string property
RichTextBox.Rtf
, so you need to read to the
char[]
buffer, convert it to string and assign.
Besides,
the whole activity with the thread won't help you to avoid some UI freezing much, because most of the time will be spent not on reading of the file, but on the assignment of
Rtf
value to the control, as the changes should be rendered. So, practically, it would be better to read the RTF file by the control itself in the UI thread.
—SA