1

I have a .net 5.0 console application. I scheduled that application exe in task scheduler. Sometimes, when I end the task, the application kills without finishing the parts I have coded to finish. (I am stopping some services, and writing things in a file if the application exiting. It needs a little bit of time.)

I tried the following command but not working. It is doing the same things.

taskkill /t /f /im "ApplicationEXEName.exe"

I am looking for a way to do wait to finish my actions if application exiting.

I had tried setting ShutdownTimeout when the application host creating like this. But it also not working.

var host = Host.CreateDefaultBuilder()
            .ConfigureAppConfiguration(ConfigConfiguration)
            .ConfigureServices((context, services) =>
            {
                services.Configure<HostOptions>(opts => opts.ShutdownTimeout = TimeSpan.FromSeconds(15));
                ConfigureDefaultServices(services);
                ConfigureServices(configuration, services);                 
            })
            .UseSerilog(Log.Logger, true)
            .Build();
TylerH
  • 20,799
  • 66
  • 75
  • 101
Emre Sevinç
  • 63
  • 1
  • 6
  • A console mode app is too simplistic to support this. You should create a service instead, OnStop() is available to shutdown cleanly. If you still need the scheduler to activate it then [look here](https://stackoverflow.com/questions/10416835/windows-service-in-task-scheduler-service-cannot-be-started-the-service-proce). – Hans Passant May 05 '22 at 16:04

1 Answers1

-1

Ok, so apparently you can do something like this

class Program
{
    static void Main( string[] args )
    {
        AppDomain.CurrentDomain.ProcessExit += ProcessExitHandler ;
    }

    static void ProcessExitHandler( object sender , EventArgs e )
    {
        throw new NotImplementedException("You can't shut me down. I quit!" ) ;
    }
}

in which case, if your application is closing, firstly this ProcessExitHandler will be called. I have never tried it though. If it works the way it is intended you might be able to pull of anything you like before the application closes.

Detect when console is being closed?

if that doesn't help I would check these:

Why does closing a console that was started with AllocConsole cause my whole application to exit? Can I change this behavior?

Capture console exit C#

  • Already I have ProcessExitHandler method. I put a breakpoint at that method and attached the process. It comes on breakpoint when I end the process on task scheduler (or taskkill command) but visual studio debug mode closing automatically in 1-2 second. Also I do not see a log on event viewer about visual studio closing. – Emre Sevinç May 05 '22 at 14:42