Featured post
multithreading - Auto file updater in C#? -
in c# m creating application based on thread, read text file computer(actually remote computer) selected user. if user makes changes in original file application should display modified file(whole).
successfully doing but, thread using don't know how , place continuous read original file background. application gets hangs code
public partial class formfileupdate : form { // delegate enables asynchronous calls setting text property on richtextbox control. delegate void updatetextcallback(object text); // thread used demonstrate both thread-safe , unsafe ways call windows forms control. private thread autoreadthread = null; public formfileupdate() { initializecomponent(); //creating thread this.autoreadthread = new thread(new parameterizedthreadstart(updatetext)); } private void opentoolstripbutton_click(object sender, eventargs e) { openfiledialog fileopen = new openfiledialog(); fileopen.title = "select text document"; fileopen.filter = @"text file|*.txt|word document|*.rtf|ms office documnet|*.doc|see files|*.*"; fileopen.filterindex = 1; fileopen.restoredirectory = true; fileopen.multiselect = false; if (fileopen.showdialog() == dialogresult.ok) { //created thread start here this.autoreadthread.start(fileopen.filename); } } private void updatetext(object filename) { streamreader readerstream = null; while(true) { if (this.richtextbox1.invokerequired) { updatetextcallback = new updatetextcallback(updatetext); this.invoke(back, new object[] { filename }); } else { try { string filetoupdate = (string)filename; readerstream = new streamreader(filetoupdate); richtextbox1.text = readerstream.readtoend(); } catch (exception ex) { messagebox.show(ex.message); } { if (readerstream != null) { readerstream.close(); thread.sleep(100); } } } } } }
additional note itay wrote:
you calling thread.sleep
gui thread! why need make delay after closing file? if need delay reason (e.g. avoid reading file frequently), don't put delay on gui thread, because make application unresponsive.
edit: answering question in comment
a possible cleaner way set timer
invoke backgroundworker
every x seconds.
the backgroundworker
makes easy run code in background thread, , have callback run on gui thread when work completed. , don't have deal invoke
, invokerequired
directly.
furthermore, create class wraps backgroundworker
make easy pass data operation of reading file (in background thread), updating ui (in gui thread).
- Get link
- X
- Other Apps
Comments
Post a Comment