views:

572

answers:

4

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.

A: 

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

RichieHindle
A: 

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. :)

JP Alioto
A: 

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;
Cris McLaughlin
+1  A: 

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, ...).

it depends
The garbage collector will do no such thing. The finalizer will call your class' finalizer method which may call Dispose.
Samuel
Thanks Samuel, I've edited accordingly. Although the link does show the destructor calling Dispose, that's not going to release managed resources either (because it's Dispose(false)). However if one is creating a public method to release a class' resources then I think one should consider implementing IDisposable.
it depends