1

I have a windows service which runs unmanaged code (using DllImport) in different threads.

Sometimes, the unmanaged code 'hangs'. Think of while (true) ;. When that happens, I need to kill the entire process (which automatically starts another because it's a windows service).

Is Environment.Exit(int) sufficient? Or will I need e.g. Environment.FailFast(string)?

Edit: I am unable to 'test' this. The freezes happen randomly.

Tvde1
  • 1,246
  • 3
  • 21
  • 41
  • 2
    What happened when you tried it? – mjwills Aug 27 '19 at 14:17
  • [Environment.FailFast](https://learn.microsoft.com/en-us/dotnet/api/system.environment.failfast?view=netframework-4.8) _"Use the Environment.FailFast method instead of the Exit method to terminate your application if the state of your application is damaged beyond repair, and executing your application's try/finally blocks and finalizers will corrupt program resources. "_ – stuartd Aug 27 '19 at 14:18

2 Answers2

1

Yes. Environment.Exit will kill all the threads running in the current process, including the main thread (and the process itself).

Environment.FailFast will log an event into the Application Log and then kill the process and all of the threads in the current process.

Robert McKee
  • 21,305
  • 1
  • 43
  • 57
1

From the official Microsoft documentation, Environment.Exit:

Terminates this process and returns an exit code to the operating system.

More usefully, the documentation goes on to state:

  • Exit always terminates an application
  • Exit terminates an application immediately, even if other threads are running

It sounds like Environment.Exit is perfectly sufficient for your needs.

Martin
  • 16,093
  • 1
  • 29
  • 48