c# - Unable to modify variables from separate thread -
so i'm making c# app has continuously read , display contents of text file, while allowing user enter text box , append end of file.
i'm doing running read
method on separate thread, changing variable stores display text-files contents what's causing problem. tried having method did this, that's not working , gave 'cross-thread-operation-not-valid' error. tried applying code found on msdn, after updating variable once thread ended!
please help.
partial class mainform { delegate void settextcallback(string text); public static string msg; public static string name; public void initclient() { name = "public.txt"; console.writeline(name); if(!file.exists(name)) { file.create(name); file.appendalltext(name, "welcome " + name); } thread read = new thread(new threadstart(this.client)); read.start(); while(!read.isalive); } public void writetext() { file.appendalltext(name, this.inputbox.text); this.inputbox.clear(); } private void settext(string text) { if (this.output.invokerequired) { settextcallback d = new settextcallback(settext); this.invoke(d, new object[] { text }); } else { this.output.text = text; } } public void client() { msg = file.readalltext(name); console.writeline(msg); thread.sleep(300); this.settext(msg); } }
why thread behaving this. how can modify code contents of output box equals of text file.
any suggestions welcome.
you've got multiple problems here,
- the use of file not thread-safe.
- your method not repeat
- your
sleep()
ing on thread
you can solve of them ditching thread , use simple timer.
Comments
Post a Comment