2

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.

UnkwnTech
  • 88,102
  • 65
  • 184
  • 229
  • 1
    dupe? or very close to: http://stackoverflow.com/questions/462903/prompt-user-to-save-when-closing-app – jcollum May 03 '09 at 23:38

4 Answers4

4

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,201
  • 2
  • 14
  • 23
1

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

codybartfast
  • 7,323
  • 3
  • 21
  • 25
  • 2
    The garbage collector will do no such thing. The finalizer will call your class' finalizer method which may call Dispose. – Samuel May 04 '09 at 01:42
  • 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. – codybartfast May 04 '09 at 18:46
0

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

RichieHindle
  • 272,464
  • 47
  • 358
  • 399
0

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
  • 44,864
  • 6
  • 88
  • 112
  • So how do you send message out? You help needed [here](http://stackoverflow.com/questions/34610819/how-do-you-dispose-a-tracelistener-properly) – deostroll Jan 05 '16 at 12:02