Run a new process in the destructor

I have a class that is responsible for handling errors. I would like to execute the process if the destructor is called. But, unfortunately, the process has not begun. New processes call exe with some arguments that should send an email. Why is this not working?

~ErrorH() { if ((int)e > 0) SendErrorMail(); } private void SendErrorMail() { if (File.Exists("C:\\Program Files (x86)\\MailSend\\MailSend.exe")) { ProcessStartInfo mailsend = new ProcessStartInfo(); mailsend.FileName = "C:\\Program Files (x86)\\MailSend\\MailSend.exe"; mailsend.Arguments = "…"; Process.Start(mailsend); } } 

If I execute the SendErrorMail function, for example, in the constructor, everything works fine. If I look at the debugger, it seems to me that I am reaching the Process.Start(mailsend); . Something went wrong? How can i fix this?

Edit

Now I used the IDisposable method. It works great, but does it use it correctly?

 class ErrorH : IDisposable { private bool disposed = false; ... public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool desposing) { if(!this.disposed) if ((int)e > 0) SendErrorMail(); disposed = true; } 

In the program, I use:

 using (Parameter p = new Parameter(args[0])) { ... } 

Inheritance of the ErrorH class from Parameter .

Greetz

+4
source share
1 answer

Instead of using destructors that cannot be called at present, use the System.IDisposable interface.

As a rule, it is bad practice to use destructors in C #, for example C ++. Since we cannot determine the exact time when the objects will be destroyed by the garbage collector (GC), C # provides an IDisposable , which has a single Dispose method that you can call either explicitly when you finish using the object or implicitly using .

+2
source

All Articles