c# - Cannot access a disposed object. Asynchronous print of messages in second form -
asynchronous print of messages in second form. system.objectdisposedexception in system.windows.forms.dll during close of second form.
mainform runs secondform. secondform runs message generator , asynchronous thread of print of messages in text box. message generator creates messages random time delay. time delay in string format message. problem - during close of second form, method secondform_closing, receive exception
system.objectdisposedexception in system.windows.forms.dll during cannot access disposed object.
public partial class mainform : form { secondform secondform; private void mainform_closing(object o, formclosingeventargs e) { environment.exit(0); } public mainform() { initializecomponent(); secondform = new secondform(); secondform.show(); } } public partial class secondform : form { private messagegenerator messagegenerator; action actprint; //this method calls objectdisposedexception point invoke in method print private void secondform_closing(object o, formclosingeventargs e) { close(); } public secondform() { initializecomponent(); messagegenerator = new messagegenerator(); actprint = new action(print); actprint.begininvoke(null, null); } public void print() { while (true) // infinite cycle { messagegenerator.createevent.waitone(); // wait event "message created" messagegenerator.createevent.reset();// event reset invoke(new methodinvoker (() => { textboxtimedelay.text = messagegenerator.message;// message print })); } } } public class messagegenerator { public autoresetevent createevent; public string message; public action actstart; public messagegenerator() { createevent = new autoresetevent(false); actstart = new action(start); actstart.begininvoke(null, null); } public void start() { random r = new random(); while (true) { int timedelay = 10 * r.next(1, 5); thread.sleep(timedelay); message = timedelay.tostring(); createevent.set(); // event "message created" } } }
solution here not realizes of resources. i.e. messagegenerator continued, , print method worked. how realizes resources ?
private void secondform_closing (object o, formclosingeventargs e) { e.cancel = true; this.hide(); this.parent = null; }
Comments
Post a Comment