Question

I'd like to properly close some sockets, and be able to tell the server that we're closing, but if the application is closed then the sockets are all just closed and on occasion files are left locked. How can I run a method when my application is closed?

This is going to go into a library that will be used in a forms app.

Was it helpful?

Solution

I would implement IDisposable on the classes that use these resources. Dispose can then be called explicitly from whichever shutdown method the application type supports (OnFormClose, OnStop, Application_End, ...).

OTHER TIPS

If its a Windows Forms application you can give focus to the form, click the events lightning bolt in the properties window, and use the Form Closing event.

this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(OnFormClosing);

private void OnFormClosing(object sender, FormClosingEventArgs e)
{
    // Your socket logic here
}

Also if you need to intercept the form being closed set the Cancel property to true:

e.Cancel = true;

Are you talking about a WinForms app? If so, use the FormClosing event on your main form.

I'm not sure if it's the best place for it, but you can tell your process is closing by hooking AppDomain.ProcessExit. It's fine for cleanup, but I don't think it's a good time to be sending any messages out. :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top