Cross-thread Operation Question

  • Thread starter Thread starter NvrBst
  • Start date Start date
N

NvrBst

I was wondering if "Cross-thread Operation Exception" (Debug Only)
happens when accessing values or is reading safe?

Exception: Cross-thread operation not valid: Control 'xxx' accessed
from a thread other than the thread it was created on.

---Example1 (produces exception in debug)---
public void FuncCalledByNewThread(object stateInfo) {
textBox1.Text = "Hello";
}

---Example2 (does not produce exception in debug)---
public void FuncCalledByNewThread(object stateInfo) {
string test = textBox1.Text;
}

---Example3 (produces exception in debug)---
public void FuncCalledByNewThread(object stateInfo) {
int index = listBox1.SelectedIndex;
}

I understand why Example1 has the exception (can lead to inconsistant
state, etc), But I don't understand why Ex2 doesn't have the
exception but Ex3 does.

Is it that reading ".Text" values is a hardcoded exception to the rule
(and thats why ".Text" is ignored if it isn't being written to, but
others arn't? Or should I be doing the following type thing even when
reading XXX.Text values?

string test;
textBox1.Invoke((Action)(() => test = textBox1.Text));


Any insight or references about why some do/some don't, or what's safe
and what isn't would be appresiated (I tried searching but coudln't
find anythign).

Thanks, NB
 
Windows form control is not inherently thread safe that means accessing the
control from multiple thread can lead the control to an inconsistent state or
can cause a deadlock situation. To help in this situation, during debugging
mode Microsoft .net framework raises an exception
"InvalidOperationException". Microsoft claims that it throws this exception
reliably during debugging however there are still some situation when it does
not throw this exception as assigning a value to a text property of a textbox.

For more information about accessing the control across different threads,
please read following article:

http://msdn.microsoft.com/en-us/library/ms171728.aspx
 
Back
Top