c# - Why would an event be null? (object reference not set to an instance of an object) -


i have form button, label , progress bar, when click button creates instance of class b run process. once process done call eventhandler show "done" in main form's label!

i created event (setstatusevent) of delegate (setstatus) this. , seems fine when call event outside eventhandler (usbforprocessexited) when call usbforprocessexited gives error -

object reference not set instance of object 

main form

public partial class main : form {     b rsset = new b();      public main()     {         initializecomponent();         rsset.setstatusevent += new remotes.setstatus(updatestatus);     }      private void button1_click(object sender, eventargs e)     {         rsset.formatusb();     }      private delegate void updatestatus(int i, string str, color clr);      private void setstatus(int i, string str, color clr)     {         this.progressbar1.value = i;         this.lbl_status.forecolor = clr;         this.lbl_status.text = str;     }      private void updatestatus(int i, string msg, color color)     {         object[] p = getinokerpara(i, msg, color);         begininvoke(new updatestatus(setstatus), p);     }      private object[] getinokerpara(int progress, string msg, color color)     {         object[] para = new object[3];         para[0] = progress;         para[1] = msg;         para[2] = color;          return para;     } } 

class b

class b {     public delegate void setstatus(int i, string msg, color color);     public event setstatus setstatusevent;      system.diagnostics.process usbfor = new system.diagnostics.process();      public void formatusb()     {          usbfor.startinfo.filename = @"usbformat.bat";         usbfor.enableraisingevents = true;         usbfor.exited += new eventhandler(usbforprocessexited);         usbfor.start();     }      public void usbforprocessexited(object sender, eventargs f)     {         setstatusevent(100, "done", color.green); //error here! (object reference not set instance of object     } } 

where problem?

you have race condition:

usbforprocessexited gets subscribed in constructor of b , might invoked before called rsset.setstatusevent += new remotes.setstatus(updatestatus).

you should call usbfor.start() after subscribed setstatusevent.

a related problem event run on thread. should set rsset.synchronizingobject before starting process event handler can modify form without manually calling invoke/begininvoke.


Comments

Popular posts from this blog

basic authentication with http post params android -

vb.net - Virtual Keyboard commands -

css - Firefox for ubuntu renders wrong colors -