سؤال

I try stop console application close but it closes before all functions is completed.. Example for stops to 90000 and then console get closed.. I want it first do all jobs end and then close console. Sorry my bad english.

Example:

    private delegate bool EventHandler(CtrlType sig);
    private enum CtrlType
    {
        CTRL_BREAK_EVENT = 1,
        CTRL_C_EVENT = 0,
        CTRL_CLOSE_EVENT = 2,
        CTRL_LOGOFF_EVENT = 5,
        CTRL_SHUTDOWN_EVENT = 6
    }
    private static EventHandler delegate0_0;
    [DllImport("Kernel32")]
    private static extern bool SetConsoleCtrlHandler(Program.EventHandler handler, bool add);
    private const int MF_BYCOMMAND = 0x00000000;
    public const int SC_CLOSE = 0xF060;

    static void Main(string[] args)
    {
        Program.delegate0_0 = (Program.EventHandler)Delegate.Combine(Program.delegate0_0, new Program.EventHandler(Program.smethod_1));
        Program.SetConsoleCtrlHandler(Program.delegate0_0, true);
        Console.ReadKey(true);
    }

    private static bool smethod_1(CtrlType enum0_0)
    {
        for (int i = 0; i < 10000000; i++)
        {
            Console.WriteLine(i);
        }

        return true;
    }
هل كانت مفيدة؟

المحلول

use EventWaitHandle on your handle in order to wait for it to be signaled. you are using unmanaged handle so this is an equivalent API to WIN32's WaitForSingleObject(HANDLE h, DWORD duaration();

so this is the C# code:

EventWaitHandle handle = new EventWaitHandle(false, EventResetMode.ManualReset);
handle.SafeWaitHandle = new Microsoft.Win32.SafeHandles.SafeWaitHandle(yourHandle,true);
handle.WaitOne();

the true in the SafeWaitHandle creation indicating that it should clean up along with the finalizer.

نصائح أخرى

You can stop it by letting the programm await for user input at the end of your programm:

Console.ReadLine();

or

Console.ReadKey();

Original Thread: How to stop C# console applications from closing automatically?

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top