c# - Alternative to using Control.Invoke -


in visual c# / .net application, have read serialport, , hence assigned datareceivedeventhandler.

however, can't of course directly change ui controls handler, because live on separate thread.

the solution appears to use control.invoke, however, have many ui actions perform, concerned perhaps i'm not taking right path.

which of following should do?

  • option a: stick invoke anyway, , perform each of actions on each of various controls using invoke each of them.

  • option b: put 50ms repeating timer, every 50ms, check if boolean datareceived == true, , if so, update ui controls accordingly. (with datareceived set true every time read data in serial port datareceivedeventhandler, , otherwise false.)

  • option c: other option?

update:

success following (based on @tcarvin's answer , @hans passant's comment).

private void datareceivedhandler(object sender, serialdatareceivedeventargs e) {    if (this.invokerequired())    {       this.begininvoke(new eventhandler<serialdatareceivedeventargs>(datareceivedhandler), new object[] { sender, e });       return;    }     tbserialstatus.text = "received text";     } 

i think on thinking this. assuming coding within form, should work. hip, might need tweak bit:

private void datareceivedhandler(object sender, serialdatareceivedeventargs e) {     if (this.invokerequired)    {       this.invoke(new eventhandler<serialdatareceivedeventargs>(datareceivedhandler), sender, e);       return;    }     // here runs on ui thread, like,     // , update many ui controls like.  } 

as can see, don't have wrap each control access in separate control.invoke.


Comments