vb.net - Update a label from a task -
i'm trying implement tasks in program. launch task produce log file, , after, want update label "log sucessfully saved".
here code
private function createlog(byval mylist list(of classtest)) dim sw new streamwriter("log_list.log") index = 1 mylist.count - 1 sw.writeline(mylist(index).comments) next sw.close() try me.invoke(updatelabel("log sucessfully saved")) catch ex exception end try return 1 end function private function updatelabel(byval text string) label1.text = text return 1 end function i launch task main form in load() :
dim tasktest = task(of integer).factory.startnew(function() createlog(thelist)) (i don't know if better use factory or declare task , task.start())
i have error on label update :
cross-thread operation not valid: control 'label1' accessed thread other thread created on.
could please explain why doesn't work invoke method ? , have alternative solution ?
thanks help
first, updatelabel should sub, not function. second, line wrong:
me.invoke(updatelabel("log sucessfully saved")) read again. are, in order, executing updatelabel function, passing result of function me.invoke (if used sub instead of function, compiler should have warned error).
this doesn't raise compiler errors because function declared without as [type] defaulted as object, can cast anything. should be:
me.invoke(sub() updatelabel("log sucessfully saved") end sub) to simplify, code can rewritten this:
private sub createlog(byval mylist list(of classtest)) dim sw new streamwriter("log_list.log") index = 1 mylist.count - 1 sw.writeline(mylist(index).comments) next sw.close() me.invoke(sub() label1.text = "log sucessfully saved" end sub) end sub
Comments
Post a Comment