vb.net - Background Workers and Successive Events -
i'm again, more code last time. may reference previous questions here , there question independent
i managed convince employer drop proprietary serial port communications library made use, starting scratch serialports , backgroundworkers know how work.
here code:
imports system imports system.io.ports public class form1 'serialport port , backgroundworker worker declared in form delegate sub appendtext_delegate(byval txtbox textbox, byval str string) private sub form1_load(sender system.object, e system.eventargs) handles mybase.load port.portname = ("com9") port.baudrate = 115200 port.parity = parity.none port.stopbits = stopbits.one port.handshake = handshake.none port.readtimeout = 1000 port.writetimeout = 1000 port.open() addhandler port.datareceived, addressof datareceived worker.workerreportsprogress = true worker.workersupportscancellation = true end sub private sub btnsend_click(sender system.object, e system.eventargs) handles btnsend.click port.write(txtinput.text & vbcrlf) end sub private sub datareceived(sender object, e serialdatareceivedeventargs) worker.runworkerasync() end sub private sub backgroundworker1_dowork(sender system.object, e system.componentmodel.doworkeventargs) handles worker.dowork if worker.cancellationpending e.cancel = true end if appendtext_threadsafe(me.txtoutput, port.readline()) end sub private sub appendtext_threadsafe(byval txtbox textbox, byval str string) if txtbox.invokerequired dim mydelegate new appendtext_delegate(addressof appendtext_threadsafe) me.invoke(mydelegate, new object() {txtbox, str}) else txtbox.appendtext(str) end if end sub end class
at moment not sure how datareceived
event , backgroundworker
work together. should put worker.runworkerasync()
calls dowork() when datareceived
event raised? should bind both events same method?
thanks help, , apologies simplicity of question. i've started backgroundworkers , still finding footing, speak.
the datareceived
event of serialport
class raised on background thread, not block ui thread , therefore don't need use backgroundworker
in case. because datareceived
called on background thread, need use invoke
if need update ui controls handler.
Comments
Post a Comment