About event registration and logoff in C #

Source: Internet
Author: User
Tags interface variables reference
Because . NETThe framework is a good encapsulation of the message-looping mechanism, and developers no longer need to have a deeper understanding WindowsEvent /The specific mechanism of message implementation, and the need to create complex event structures and so-called message handles. All we have to do is-- 1, using overloaded operators " +="Register an event; 2and write a method for handling the event. (For an Introduction to event handling in c#2.0, see my article: c#2.0 generic Proxies and events: With a thrill of the hundred So simple, so accustomed to the Win32The programmers of the program scoff, ironically: "We are professionals in the hands of the car, you . NETA family can only play with automatic files. What the? You also read the first words D》? Can you read it? ” . ..Ignore them! Let's talk about our. and flung them before their heads: "Pedantic !”。 If not, then quote a jiehen: "We are never happy to change our work habits, just like putting a picture of a wife under a lamp." However, why should we be stubborn when a new approach does greatly improve our efficiency and action? "--Is it effective? Anyway A few days ago, when I was writing the event communication between the main form and the child module, I encountered an extremely depressing problem. Before saying this question, I and everybody explained my design mentality.

main form frmmain : iparentform ) Event Member:
public event Parenteventhandler onuserlistcreated;   Event handling method: void todoonrequestuserlist (object sender, EventArgs e) {         // Create datatable DT           ...          this.onuserlistcreated (this, new Parenteventargs (DT));   a row registers the child form event:

Child form (frmchild) Event Member:
public event EventHandler onuserlistcreated; Event handling method:void todoonrequestuserreturned (object sender, Parenteventargs e) {} in an event that registers the main form in the OnLoad event-handling method:(this. MdiParent as Iparentform). onuserlistcreated + = new Parenteventhandler (todoonrequestuserreturned);

The main form object is Frmmain, it realizes the Iparentforminterface, which defines an event member onuserlistcreated (It's EventArgsFor custom Parenteventargs)。 FrmmainObject creates a subform somewhere Frmchild, and registered a Frmchildof events onrequestuserlist。 Child Form Object FrmchildWhen loading (OnLoadMethod in )Get FrmmainThe reference, and registered the Frmmainof events onuserlistcreated。 Depending on the business logic, the user behavior triggers the event at a time when the subform is running onrequestuserlist, at this time FrmmainThis event is captured and its own processing method is invoked to generate a list of requested users (DataTable)。 And then FrmmainIssued an event onuserlistcreatedComplete with the prompt list, and you will have just created the DataTableAs ParenteventargsParameter inserts the event. The subform then receives the event and, in its own event-handling method, the DataTableConduct their own business logic actions. In the next run of the program, the lovely code happy to execute smoothly . ..But it's not a short-lived! When I close the Open subform and reopen it, the main form is triggered onuserlistcreatedCall target exception occurs after an event ,The subform is also thrown in the handling method of the event NullReferenceExceptionAbnormal (Object reference not set to object instance )。 When I am in the subform event handling method todoonrequestuserreturnedWhen you set breakpoints in debugging, you find that all the controls and variables are NULL!! It's called melancholy. . ..On the bus, on foot, on the toilet, before falling asleep, I reckoned that this supernatural phenomenon was inextricably linked to the sudden disappearance of the nearest neighbor's cat. . ..Of course, as a Christian, I also fear that this is the Lord, Jesus Christ for me to cross the road the day before the punishment . ..Helpless, I was exceedingly blind in FrmchildOf todoonrequestuserreturnedA single line of statements was added to the method: " Messagebox.showdialog ("So boring a thing!")"To vent his feelings. Save, compile, run--the face of the big bad guy is exposed! When I first opened the subform, as I expected, the program works and pops up. MessageBox。 The point is, when I close the child window and open it for the second time, MessageBoxpopped up two times! Well . ..With doubt, I repeat the above closing and opening steps, MessageBoxpopped up three times! -Things are already going on. After I've been thinking about it for a while (maybe someone will call me a rookie. . ..And finally understand the reason for everything: Because the program is always running, the main form object resides in memory and maintains its state (it does not have disposed, so each time the subform is created, the main form registers its onrequestuserlistevent, similarly, when the subform is loaded, itself will also take the main form's onuserlistcreatedEvent is registered once. The problem is here, though the subform is off, and disposedOut. However, it closes without logging off the event registered with the main form. As the subform opens again and again, the main form's onuserlistcreated's Been +=Had NA lot of registered users, of which the N-1A user is not already there, and the main form is completely unknown. So when issuing onuserlistcreatedEvent, the main form will also call this with no indomitable NMore than one method agent, which inevitably causes an exception to be thrown--the only open subform receives a repeated event and attempts to invoke todoonuserlistreturnedmethod, if this method contains an action on a member variable of this object, it naturally leads to an exception where the reference is not set to an object instance. Maybe a friend would ask why the main form calls those already disposedOf FrmchildThe agent of the method that is currently present FrmchildExecute it? I think this may be due to the fact that the same method of the class instance is shared in the memory stack, while the member variables are stored in the heap, each maintaining its state, and when the object to which it belongs is freed, its value is NULLOut. (Personal opinion, looking at brothers and sisters to correct) in summary, I make a conclusion: when a subform is closed, it should unregister its own registered main form object (or a long resident memory object) event one by one. For example, in this example, the subform onclosedThe following code is added to the event-handling method:
(this. MdiParent as Iparentform). onuserlistcreated-= new Parenteventhandler (todoonrequestuserreturned)In order to trigger the execution of a method of a subform only after an operation has been performed on the main form, we usually do not use the event mechanism, and we use the following two methods:

A.Change this method access property to PublicAnd is then invoked by the main form at the appropriate time.
B.Defines an interface that implements this interface by the subform object and promotes the target method to the members of that interface. This interface member method is called at the appropriate time by the main form. April Fools ' Day just passed, hope Dear Programmer not drugged

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.