I have written a C# Windows Forms application, not a service (it is only used when the user is logged in and has a graphical user interface) that has a background thread run
Take a look at the Microsoft.Win32.SystemEvents.SessionEnding event.