c# - Threading Basics -
using system; using system.collections.generic; using system.componentmodel; using system.data; using system.drawing; using system.linq; using system.text; using system.windows.forms; using system.threading; namespace testthreads { public partial class form1 : form { public form1() { initializecomponent(); } private void form1_load(object sender, eventargs e) { } public void counttolots() { (int = 0; < 10000000; i++) { textbox1.text = "counting 10000000, value " + + environment.newline; } } public void counttozero() { (int = 10000000; > 0; i--) { textbox2.text = "counting 0, value " + + environment.newline; } } private void button1_click(object sender, eventargs e) { thread countup = new thread(new threadstart(counttolots)); thread countdown = new thread(new threadstart(counttozero)); countup.start(); countdown.start(); } private void button2_click(object sender, eventargs e) { textbox3.text = "bobby bob bob " + environment.newline; } } }
i need try , hang of - dont understand theory behind why error message. me out please?
cross-thread operation not valid: control 'textbox1' accessed thread other thread created on.
ui controls have "thread affinity"; do not want touched except ui thread; includes reading , writing properties. assignment .text
should done ui thread, either using invoke
, or backgroundworker
.
for example:
public void counttolots() { (int = 0; < 10000000; i++) { // running on bg thread textbox1.invoke((methodinvoker) delegate { // running on ui thread textbox1.text = "counting 10000000, value " + + environment.newline; }); // running on bg thread again } }
but note type of thread switching has overhead. should not call every iteration - should (for example) update ui every [n] iterations - in above, every 10000 example.
Comments
Post a Comment