0

I'm writing a class library (for .Net Framework 4.7.2) that has methods that involve flushing a file. This flushing should be done in response to direct method calls, but also if the calling application exits early.

If I was writing code within a WinForms application, I could use

System.Windows.Forms.Application.ApplicationExit += FlushHandler;

to add a handler to the ApplicationExit event and

System.Windows.Forms.Application.ApplicationExit -= FlushHandler;

to remove that handler.

Within a class library, I receive the message:

The type or namespace name 'Forms' does not exist in the namespace 'System.Windows' (are you missing an assembly reference?)

How can I do something similar to the above within a class library, where the application exit event to handle is the closing of the calling WinForms application?

Sepia
  • 447
  • 6
  • 21
  • 2
    You could try to use the ProcessExit-event of the AppDomain class; see https://stackoverflow.com/questions/1119841/net-console-application-exit-event – Matze Nov 18 '19 at 13:46
  • 1
    Why would you want to do it ? DLL library usually contains code that can be loaded by multiple applications and platforms. Usually it is not designed to be run-time specific and it doesn't use platform specific events. You could create and expose delegate in DLL and hook it to the event from the project that is utilizing it – Fabjan Nov 18 '19 at 13:46
  • 1
    As long as your library will only be run in a Forms application, then that would work. But as it says, you will need to [add a reference](https://learn.microsoft.com/en-us/visualstudio/ide/how-to-add-or-remove-references-by-using-the-reference-manager?view=vs-2019#add-a-reference) to `System.Windows.Forms`. – Gabriel Luci Nov 18 '19 at 13:47
  • 1
    Check this answer: https://stackoverflow.com/questions/4646827/on-exit-for-a-console-application – Fabjan Nov 18 '19 at 13:57
  • @Fabjan In this case, the DLL will only be used by WinForms applications I am writing, so making it runtime-specific is fine. – Sepia Nov 18 '19 at 15:17

1 Answers1

3

If you are using using FileStream to access the file you don't have to use a seperate FlushHandler.

The FileStream will perform a flush on its disposale.

epanalepsis
  • 853
  • 1
  • 9
  • 26
  • But what if someone closes the app before it was disposed ? – Fabjan Nov 18 '19 at 13:53
  • Usually the disposale should still be executed when a `using` block is used. Though there are some cases where the disposale will not be executed like critical system crashs or power issues. But in those cases you won't be able to do anything else either. – epanalepsis Nov 18 '19 at 14:01
  • 1
    Having tried it out for a while in the Visual Studio debugger, the Dispose methods of objects created in other threads are indeed called correctly when the application exits, provided they are initialised through a using statment. I plan to accept this answer later. – Sepia Nov 18 '19 at 15:51