c# - how to update a form from a thread -


i using mod bus protocol retrieve data board. want update data in window form time. label update when click button, problem coding?

private void call() {

                {             requestdata(); //get data mod bus              run(a.tostring());           } while (operation);      }      delegate void callmethod(string data);      private void run(string data) {          if (this.labelo2.invokerequired)         {             setrichboxcallback d = new setrichboxcallback(run);             this.invoke(d, new object[] { data });         }         else {             labelo2.text = data;         }      }     thread thread;     private void button1_click(object sender, eventargs e)     {          thread = new thread(new threadstart(call));         thread.start();      }    public void requestdata()     {          if (writeserialport(setmessage, 0, 8))         {             thread.sleep(1000);             (i = 0; < 19; i++)             {                  mm[i] = (byte)serialportboard.readbyte();               }              = mm[11] << 8 | mm[12];             b = (int)mm[13] << 8 | mm[14];           }      } 

just call ui updates should wrapped within invokerequired ... pattern - not fetch of data port. invokerequired... pattern missing else.

delegate void uiupdate(object a, object b);  public void requestdata() {   ...   // set type , real value here ;)   object = null, b = null;   var call = new uiupdate((pa,pb) => {       labelbin.text = pa.tostring();       labelo2.text = pb.tostring();   });   if (this.invokerequired) {     this.invoke(call, a, b);   } else {     call.invoke(a, b);   }       }  private void button1_click(object sender, eventargs e) {   new thread(() => {     {       requestdata();  // data mod bus protocol     } while (operation);   }).start();     } 

edit:

also there should 1 reader thread; reading; not write/read in 1 thread. reader thread should started on form load or in form constructor.

writeserialport(setmessage, 0, 8) 

should invoked directly on button click, while read should in single (separate) thread.


Comments

Popular posts from this blog

database - VFP Grid + SQL server 2008 - grid not showing correctly -

jquery - Set jPicker field to empty value -

.htaccess - htaccess convert request to clean url and add slash at the end of the url -