Frage

Ich habe eine Konsolenanwendung, die ziemlich viele Threads enthält.Es gibt Threads, die bestimmte Bedingungen überwachen und das Programm beenden, wenn sie wahr sind.Diese Kündigung kann jederzeit erfolgen.

Ich benötige ein Ereignis, das beim Schließen des Programms ausgelöst werden kann, damit ich alle anderen Threads bereinigen und alle Dateihandles und Verbindungen ordnungsgemäß schließen kann.Ich bin mir nicht sicher, ob bereits eines in das .NET-Framework integriert ist, also frage ich nach, bevor ich mein eigenes schreibe.

Ich habe mich gefragt, ob es ein Ereignis in der Art von Folgendem gab:

MyConsoleProgram.OnExit += CleanupBeforeExit;
War es hilfreich?

Lösung

Ich bin nicht sicher, wo ich den Code im Internet gefunden, aber ich fand es jetzt in einem meiner alten Projekte. Dies ermöglicht es Ihnen Bereinigungscode in Ihrer Konsole zu tun, zum Beispiel wenn es abrupt geschlossen oder aufgrund einer Abschaltung ...

[DllImport("Kernel32")]
private static extern bool SetConsoleCtrlHandler(EventHandler handler, bool add);

private delegate bool EventHandler(CtrlType sig);
static EventHandler _handler;

enum CtrlType
{
  CTRL_C_EVENT = 0,
  CTRL_BREAK_EVENT = 1,
  CTRL_CLOSE_EVENT = 2,
  CTRL_LOGOFF_EVENT = 5,
  CTRL_SHUTDOWN_EVENT = 6
}

private static bool Handler(CtrlType sig)
{
  switch (sig)
  {
      case CtrlType.CTRL_C_EVENT:
      case CtrlType.CTRL_LOGOFF_EVENT:
      case CtrlType.CTRL_SHUTDOWN_EVENT:
      case CtrlType.CTRL_CLOSE_EVENT:
      default:
          return false;
  }
}


static void Main(string[] args)
{
  // Some biolerplate to react to close window event
  _handler += new EventHandler(Handler);
  SetConsoleCtrlHandler(_handler, true);
  ...
}

Aktualisieren

Für diejenigen, die nicht die Kommentare überprüfen es scheint, dass diese spezielle Lösung hat nicht funktioniert gut (oder überhaupt) auf Windows 7 . Die folgende fädeln spricht über dieses

Andere Tipps

Vollarbeits Beispiel arbeitet mit Strg-C, die Fenster mit X schließen und töten:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;

namespace TestTrapCtrlC {
    public class Program {
        static bool exitSystem = false;

        #region Trap application termination
        [DllImport("Kernel32")]
        private static extern bool SetConsoleCtrlHandler(EventHandler handler, bool add);

        private delegate bool EventHandler(CtrlType sig);
        static EventHandler _handler;

        enum CtrlType {
            CTRL_C_EVENT = 0,
            CTRL_BREAK_EVENT = 1,
            CTRL_CLOSE_EVENT = 2,
            CTRL_LOGOFF_EVENT = 5,
            CTRL_SHUTDOWN_EVENT = 6
        }

        private static bool Handler(CtrlType sig) {
            Console.WriteLine("Exiting system due to external CTRL-C, or process kill, or shutdown");

            //do your cleanup here
            Thread.Sleep(5000); //simulate some cleanup delay

            Console.WriteLine("Cleanup complete");

            //allow main to run off
            exitSystem = true;

            //shutdown right away so there are no lingering threads
            Environment.Exit(-1);

            return true;
        }
        #endregion

        static void Main(string[] args) {
            // Some boilerplate to react to close window event, CTRL-C, kill, etc
            _handler += new EventHandler(Handler);
            SetConsoleCtrlHandler(_handler, true);

            //start your multi threaded program here
            Program p = new Program();
            p.Start();

            //hold the console so it doesn’t run off the end
            while (!exitSystem) {
                Thread.Sleep(500);
            }
        }

        public void Start() {
            // start a thread and start doing some processing
            Console.WriteLine("Thread started, processing..");
        }
    }
}

Überprüfen Sie auch:

AppDomain.CurrentDomain.ProcessExit

Es klingt wie Sie die Fäden direkt die Anwendung beendet haben? Vielleicht wäre es besser, ein Faden zu haben, das Hauptthread Signal zu sagen, dass die Anwendung beendet werden soll.

Auf Empfang dieses Signals kann der Haupt-Thread Abschaltung sauber die anderen Fäden und schließlich schließen sich nach unten.

Es gibt Apps für WinForms;

Application.ApplicationExit += CleanupBeforeExit;

Versuchen Sie es mit Konsolen-Apps

AppDomain.CurrentDomain.DomainUnload += CleanupBeforeExit;

Ich bin mir jedoch nicht sicher, wann das aufgerufen wird oder ob es innerhalb der aktuellen Domäne funktioniert.Ich vermute nicht.

Ich habe ein ähnliches Problem hat, nur meine Konsole App mit einer präemptiven Aussage über Mitte in Endlosschleife laufen würde. Hier ist meine Lösung:

class Program
{
    static int Main(string[] args)
    {
        // Init Code...
        Console.CancelKeyPress += Console_CancelKeyPress;  // Register the function to cancel event

        // I do my stuffs

        while ( true )
        {
            // Code ....
            SomePreemptiveCall();  // The loop stucks here wating function to return
            // Code ...
        }
        return 0;  // Never comes here, but...
    }

    static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
    {
        Console.WriteLine("Exiting");
        // Termitate what I have to terminate
        Environment.Exit(-1);
    }
}

Zerokelvin Antwort funktioniert in Windows 10 x64, .NET 4.6 Konsolenanwendung. Für diejenigen, die nicht brauchen, mit dem CtrlType Enum zu beschäftigen, hier ist eine wirklich einfache Art und Weise in den Rahmen des Herunterfahren Haken:

class Program
{
    private delegate bool ConsoleCtrlHandlerDelegate(int sig);

    [DllImport("Kernel32")]
    private static extern bool SetConsoleCtrlHandler(ConsoleCtrlHandlerDelegate handler, bool add);

    static ConsoleCtrlHandlerDelegate _consoleCtrlHandler;

    static void Main(string[] args)
    {
        _consoleCtrlHandler += s =>
        {
            //DoCustomShutdownStuff();
            return false;   
        };
        SetConsoleCtrlHandler(_consoleCtrlHandler, true);
    }
}

FALSCH aus dem Handler Rückkehr erzählt den Rahmen, die wir nicht „Handhabung“ sind das Steuersignal, und die nächste Handler-Funktion in der Liste der Handler für diesen Prozess verwendet wird. Falls keine der Handler TRUE zurückgibt, wird die Standard-Handler genannt.

Beachten Sie, dass, wenn der Benutzer eine Abmeldung oder Shutdown durchführt, wird der Rückruf von Windows nicht genannt, sondern wird sofort beendet.

Visual Studio 2015 + Windows-10

  • Zulassen für die Bereinigung
  • Single Instance App
  • Einige Goldplating

Code:

using System;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;

namespace YourNamespace
{
    class Program
    {
        // if you want to allow only one instance otherwise remove the next line
        static Mutex mutex = new Mutex(false, "YOURGUID-YOURGUID-YOURGUID-YO");

        static ManualResetEvent run = new ManualResetEvent(true);

        [DllImport("Kernel32")]
        private static extern bool SetConsoleCtrlHandler(EventHandler handler, bool add);                
        private delegate bool EventHandler(CtrlType sig);
        static EventHandler exitHandler;
        enum CtrlType
        {
            CTRL_C_EVENT = 0,
            CTRL_BREAK_EVENT = 1,
            CTRL_CLOSE_EVENT = 2,
            CTRL_LOGOFF_EVENT = 5,
            CTRL_SHUTDOWN_EVENT = 6
        }
        private static bool ExitHandler(CtrlType sig)
        {
            Console.WriteLine("Shutting down: " + sig.ToString());            
            run.Reset();
            Thread.Sleep(2000);
            return false; // If the function handles the control signal, it should return TRUE. If it returns FALSE, the next handler function in the list of handlers for this process is used (from MSDN).
        }


        static void Main(string[] args)
        {
            // if you want to allow only one instance otherwise remove the next 4 lines
            if (!mutex.WaitOne(TimeSpan.FromSeconds(2), false))
            {
                return; // singleton application already started
            }

            exitHandler += new EventHandler(ExitHandler);
            SetConsoleCtrlHandler(exitHandler, true);

            try
            {
                Console.BackgroundColor = ConsoleColor.Gray;
                Console.ForegroundColor = ConsoleColor.Black;
                Console.Clear();
                Console.SetBufferSize(Console.BufferWidth, 1024);

                Console.Title = "Your Console Title - XYZ";

                // start your threads here
                Thread thread1 = new Thread(new ThreadStart(ThreadFunc1));
                thread1.Start();

                Thread thread2 = new Thread(new ThreadStart(ThreadFunc2));
                thread2.IsBackground = true; // a background thread
                thread2.Start();

                while (run.WaitOne(0))
                {
                    Thread.Sleep(100);
                }

                // do thread syncs here signal them the end so they can clean up or use the manual reset event in them or abort them
                thread1.Abort();
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.Write("fail: ");
                Console.ForegroundColor = ConsoleColor.Black;
                Console.WriteLine(ex.Message);
                if (ex.InnerException != null)
                {
                    Console.WriteLine("Inner: " + ex.InnerException.Message);
                }
            }
            finally
            {                
                // do app cleanup here

                // if you want to allow only one instance otherwise remove the next line
                mutex.ReleaseMutex();

                // remove this after testing
                Console.Beep(5000, 100);
            }
        }

        public static void ThreadFunc1()
        {
            Console.Write("> ");
            while ((line = Console.ReadLine()) != null)
            {
                if (line == "command 1")
                {

                }
                else if (line == "command 1")
                {

                }
                else if (line == "?")
                {

                }

                Console.Write("> ");
            }
        }


        public static void ThreadFunc2()
        {
            while (run.WaitOne(0))
            {
                Thread.Sleep(100);
            }

           // do thread cleanup here
            Console.Beep();         
        }

    }
}

Die Link oben von Charle B in Kommentar zu FLQ genannten

Tief unten sagt:

  

SetConsoleCtrlHandler nicht auf Windows7 arbeiten, wenn Sie zu user32 verknüpfen

Einige wo sonst im Gewinde ist es Kiste ein ausgeblendetes Fenster vorgeschlagen. So erstelle ich eine winform und in onload angebracht ich original Haupt zu trösten und auszuführen. Und dann SetConsoleCtrlHandle funktioniert gut (SetConsoleCtrlHandle genannt wird, wie durch FLQ vorgeschlagen)

public partial class App3DummyForm : Form
{
    private readonly string[] _args;

    public App3DummyForm(string[] args)
    {
        _args = args;
        InitializeComponent();
    }

    private void App3DummyForm_Load(object sender, EventArgs e)
    {
        AllocConsole();
        App3.Program.OriginalMain(_args);
    }

    [DllImport("kernel32.dll", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool AllocConsole();
}

Für Interessenten in VB.net. (Ich habe das Internet gesucht und konnte nicht ein Äquivalent für sie finden) Hier ist es in vb.net übersetzt wird.

    <DllImport("kernel32")> _
    Private Function SetConsoleCtrlHandler(ByVal HandlerRoutine As HandlerDelegate, ByVal Add As Boolean) As Boolean
    End Function
    Private _handler As HandlerDelegate
    Private Delegate Function HandlerDelegate(ByVal dwControlType As ControlEventType) As Boolean
    Private Function ControlHandler(ByVal controlEvent As ControlEventType) As Boolean
        Select Case controlEvent
            Case ControlEventType.CtrlCEvent, ControlEventType.CtrlCloseEvent
                Console.WriteLine("Closing...")
                Return True
            Case ControlEventType.CtrlLogoffEvent, ControlEventType.CtrlBreakEvent, ControlEventType.CtrlShutdownEvent
                Console.WriteLine("Shutdown Detected")
                Return False
        End Select
    End Function
    Sub Main()
        Try
            _handler = New HandlerDelegate(AddressOf ControlHandler)
            SetConsoleCtrlHandler(_handler, True)
     .....
End Sub
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top