c#


How to detect when application terminates?


This is a follow up to my initial question and I would like to present my findings and ask for corrections, ideas and insights. My findings (or rather interpretations) come from people's answers to my previous question, reading MSDN .NET 3.5 documentation and debugging .NET 3.5 code. I hope this will be of value to someone who was wondering like me how to detect when an application terminates.
Events:
System.AppDomain.CurrentDomain.ProcessExit: raised when process exits, e.g. after the default AppDomain and everything else was unloaded [Total execution time is limited to just 3 seconds!]. For WPF, use System.Windows.Application.Exit instead. For Windows Forms, run code after Application.Run(...) in main method.
System.AppDomain.CurrentDomain.DomainUnload: raised when an AppDomain other than default AppDomain unloads, e.g. when running classes with unit testing frameworks (MbUnit with TestDriven.NET).
System.AppDomain.CurrentDomain.UnhandledException: (if handled in default AppDomain:) raised for any unhandled exception in any thread, no matter what AppDomain the thread started in. This means, this can be used as the catch-all for all unhandled exceptions.
System.Windows.Application.Exit: raised when WPF application (i.e. the default AppDomain) exits gracefully. Override System.Windows.Application.OnExit to take advantage of it.
Finalizers (destructors in C#): run when garbage collector frees unmanaged resources. [Total execution time is limited!].
Order of events:
WPF application: graceful exit
System.Windows.Application.Exit
System.AppDomain.CurrentDomain.ProcessExit
Finalizers
WPF application: unhandled exception
System.AppDomain.CurrentDomain.UnhandledException
MbUnit running inside TestDriven.NET: passed test (graceful exit)
System.AppDomain.CurrentDomain.DomainUnload
Finalizers
MbUnit running inside TestDriven.NET: failed test (unhandled exceptions are handled by MbUnit)
AppDomain.CurrentDomain.DomainUnload
Finalizers
Questions:
Are my interpretations/findings correct?
Do you know of more details that I have
left out? E.g. what is the total
execution time for finalizers?
Do you know of any other events /
ideas that I be aware of?
What events are there and what order do they get raised in other applications, e.g. Windows Forms, Web Service, ASP.NET web site, etc?
Prompted by ssg31415926's question/answer (this question is a bit reversed), there's also Application.SessionEnding which is called when the when the user logs off or shuts down. It is called before the Exit event.
The default timeout for a finalizer's execution is 2 seconds.
When Dispatcher.BeginInvokeShutdown() is called, Application.Exit will not be called.
You write:
System.AppDomain.CurrentDomain.UnhandledException: (if handled in default AppDomain:) raised for any unhandled exception in any thread, no matter what AppDomain the thread started in. This means, this can be used as the catch-all for all unhandled exceptions.
I do not think that this is correct. Try the following code:
using System;
using System.Threading;
using System.Threading.Tasks;
namespace AppDomainTestingUnhandledException
{
class Program
{
static void Main(string[] args)
{
AppDomain.CurrentDomain.UnhandledException +=
(sender, eventArgs) => Console.WriteLine("Something went wrong! " + args);
var ad = AppDomain.CreateDomain("Test");
var service =
(RunInAnotherDomain)
ad.CreateInstanceAndUnwrap(
typeof(RunInAnotherDomain).Assembly.FullName, typeof(RunInAnotherDomain).FullName);
try
{
service.Start();
}
catch (Exception e)
{
Console.WriteLine("Crash: " + e.Message);
}
finally
{
AppDomain.Unload(ad);
}
}
}
class RunInAnotherDomain : MarshalByRefObject
{
public void Start()
{
Task.Run(
() =>
{
Thread.Sleep(1000);
Console.WriteLine("Uh oh!");
throw new Exception("Oh no!");
});
while (true)
{
Console.WriteLine("Still running!");
Thread.Sleep(300);
}
}
}
}
As far as I can tell, the UnhandledException handler is never called, and the thread will just silently crash (or nag at you if you run it in the debugger).
Just add a new event on your main form:
private void frmMain_Load(object sender, EventArgs e)
{
Application.ApplicationExit += new EventHandler(this.WhenItStopsDoThis);
}
private void WhenItStopsDoThis(object sender, EventArgs e)
{
//Program ended. Do something here.
}

Related Links

Windows phone: Combine images and make a video file
How do I capture lost focus on a Textbox?
How to Read a text file after skipping specified number of lines in C#
Deleting all same values from Generic List
How do I create a workspace with local folder mappings in tfs using C#
2D array simple issue
How do I set my item[“Explanatory Text”] equal to public class ExpandedHomeSlider string ExplanatoryText and then add it to my expandedSliderList?
Index out of bounds in c# while using this code
Reduce the main form code by deferring it other classes
Adding string value to DataGrid in C#?
Is it a bad design decision to expose an enumeration in web API which is consumed by multiple clients? [closed]
How to write this linq query dynamically c#
Inconsistent behavior: The ntext and image data types cannot be used in WHERE, HAVING, GROUP BY, ON, or IN clauses
If statement code clarification
DataGridView Different cell formatting in same column possible?
Animate circle's fill using sine-wave

Categories

HOME
logging
oop
javafx
kendo-ui-angular2
azure-documentdb
stanford-nlp
oracle-sqldeveloper
compression
postgresql-9.3
glsl
datetimepicker
browser-cache
yuv
genexus
revit-api
ios-universal-links
oms
activejdbc
wowza
osclass
solidity
openstack-horizon
pylint
simd
vivado-hls
openam
glibc
gomobile
ejb-3.1
serenity-js
include-path
aws-iot
poisson
rancher
ballerinalang
utc
launchd
typeclass
wordpress-rest-api
slim-lang
node-soap
offset
openvms
perf
realloc
jquery-inputmask
ui-grid
file-descriptor
google-cloud-powershell
collation
head
scrapinghub
spring-data-commons
remap
ionic2-select
cloudconvert
vertex
multi-targeting
tsc
ownership
vga
nimbus
hotkeys
diameter-protocol
pyshark
code-translation
containstable
nslocalizedstring
dday
jts
persian
personality-insights
pushwoosh
bootstrap-tabs
cyberduck
firewire
euro
web-standards
vectordrawable
system.diagnostics
nfa
crtdbg.h
aiff
kss
diffmerge
pyalgotrade
reactjs-native
windows-phone-store
xml-validation
tlbimp
outlook-object-model
cocotron
microsoft-speech-platform
m3u
erlide
commonsware
joomla1.7
recess
simultaneous
oaw
system-analysis
numerical-computing
mysql-pconnect
helios
focus-stealing
zend-acl

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App