vb.net - Cannot update UI from other task in win forms? -
i have 4 complex tasks running parallel, want update rich textbox log file. approximate program structure follows:
sub buttonclick () complextask1 'code goes here complextask2 'code goes here complextask3 'code goes here complextask4 'code goes here end sub
the above 4 tasks updates log file, have display in richtextbox
control. tried infinite while
loop, , updating textbox
, ui
getting hanged.
you must run heavy task in separate thread or background worker first read , study threading here sample coding task import these form class
imports system.threading imports system.componentmodel
create local variable in form
private synccontext synchronizationcontext
create method task
private sub dotask() complextask1 'code goes here complextask2 'code goes here complextask3 'code goes here complextask4 'code goes here end sub
on button click create new thread , execute heavy task
sub buttonclick () synccontext = asyncoperationmanager.synchronizationcontext() dim newthread thread newthread = new thread(addressof dotask) newthread.start() end sub
to update ui status create 1 method it
private sub updatestatus(byval state object) dim mytext string = ctype(state, string) end sub
now call ui method use following statement in dotask method
dim newstatus string = “this new status” synccontext.post(new sendorpostcallback(addressof updatestatus), newstatus)
complete code this
imports system.threading imports system.componentmodel public class form1 private synccontext synchronizationcontext private sub buttonclick () synccontext = asyncoperationmanager.synchronizationcontext() dim newthread thread newthread = new thread(addressof dotask) newthread.start() end sub private sub dotask() dim newstatus string complextask1 'code goes here newstatus=”new task done” synccontext.post(new sendorpostcallback(addressof updatestatus), newstatus) complextask2 'code goes here newstatus=”new task done” synccontext.post(new sendorpostcallback(addressof updatestatus), newstatus) complextask3 'code goes here newstatus=”new task done” synccontext.post(new sendorpostcallback(addressof updatestatus), newstatus) complextask4 'code goes here newstatus=”new task done” synccontext.post(new sendorpostcallback(addressof updatestatus), newstatus) end sub private sub updatestatus(byval state object) dim mytext string = ctype(state, string) end sub end class
Comments
Post a Comment