C# .NET - Calling main function - Asked By Anandh Ramanujam on 15-Feb-12 09:16 AM

Hi,

I have written a program in console application, it performs a job. If any error occurs, handle it, write it in a log and exit the application.

I have used this exe in windows job scheduler and made it run once a day.

Now, I want, if that particular exception occurs, I need to run the .exe again immediately..

Is any possibility to do that.

Thanks.




Amit Choudhary replied to Anandh Ramanujam on 15-Feb-12 09:30 AM
Yes you can execute that exe as
          System.Diagnostics.Process objProc =  new Process();
          objProc.StartInfo.FileName =  <EXEPATH>;
          objProc.StartInfo.Arguments = sArguements;

          //call the Start method of instance.
          objProc.Start();
        objProc.WaitForExit();  //Run in syncronised way
Peter Bromberg replied to Anandh Ramanujam on 15-Feb-12 10:33 AM

Thread.GetDomain().UnhandledException += new 
UnhandledExceptionEventHandler(Application_UnhandledException);

public static void Application_UnhandledException(
object sender, UnhandledExceptionEventArgs e)
{
//  re-run the executable here using Process.Start method

}

[)ia6l0 iii replied to Anandh Ramanujam on 15-Feb-12 12:19 PM
The answer lies in your statement and the sequence of actions you perform. 

You say - "I have written a program in console application, it performs a job. If any error occurs, handle it, write it in a log and exit the application.". So after an error occurs - you deviate from the current action and continue to execute some code. 

For this, you should modularize your code, and write them into resuable functions. Ensure that you call the same function again when it errors out. 

public void DoWork(string argument)
{}

void Main()
{
try
{
Dowork("obama");
}
catch (Exception ex)
{
//Log exception
//Call Dowork again

}
}

This assumes that you have your reusable code in the Dowork function. Call it when it errors as well. But I doubt if it is really gonna solve your problem. You should probably add a timer or something else for a good wait time, so that the exe does not get into infinite execution. 

And yes, you should break out of this after a certain number of retries :-;

Hope that helps.