c# - Using Console.ReadKey() after calling AttachConsole(-1) hangs application on ReadKey() -


currently i'm trying best have single application can used via command prompt or via windows form application. application used service well. because of obvious reasons (like rewriting code , keeping changes 2 applications) want create 1 application.

currently i'm using following method make happen (i have included debugging code in case had specific suggestions)...

using system; using system.collections.generic; using system.io; using system.linq; using system.reflection; using system.runtime.interopservices; using system.serviceprocess; using system.text; using system.threading; using system.threading.tasks; using system.windows.forms;  namespace myapplicationspace {     static class program     {         #region private class apis         [dllimport("kernel32.dll", setlasterror = true)]         private static extern bool attachconsole(int pid);          [dllimport("kernel32")]         private static extern bool allocconsole();          [dllimport("kernel32.dll", setlasterror = true)]         private static extern bool freeconsole();         #endregion          #region constructor         /// <summary>         /// main entry point application.         /// </summary>         private static void main(string[] args)         {             if (args.contains("-service"))             {                 servicebase[] servicestorun;                 servicestorun = new servicebase[]                 {                 new myserviceclass()                 };                  if (environment.userinteractive)                 {                     if (!attachconsole(-1)) allocconsole();                      runinteractive(servicestorun);                      freeconsole();                     sendkeys.sendwait("{enter}");                 }                 else                     servicebase.run(servicestorun);             }             else             {                 application.enablevisualstyles();                 application.setcompatibletextrenderingdefault(false);                 application.run(new form1());             }         }         #endregion          #region private class functions         private static void runinteractive(servicebase[] servicestorun)         {             console.writeline("services running in interactive mode.");             console.writeline();              methodinfo onstartmethod = typeof(servicebase).getmethod("onstart", bindingflags.instance | bindingflags.nonpublic);             foreach (servicebase service in servicestorun)             {                 console.write("starting {0}...", service.servicename);                 onstartmethod.invoke(service, new object[] { new string[] { } });                 console.write("started");             }              console.writeline();             console.writeline();             console.writeline("press key stop services , end process...");             console.writeline("before readkey");              file.writealltext(appdomain.currentdomain.basedirectory + "error.log", "before readkey");             try             {                 console.readkey();             }             catch (exception ex)             {                 file.writealltext(appdomain.currentdomain.basedirectory + "error.log", ex.message);             }             file.writealltext(appdomain.currentdomain.basedirectory + "error.log", "after readkey");              console.writeline("after readkey");             console.writeline();              console.writeline("continuing...");              methodinfo onstopmethod = typeof(servicebase).getmethod("onstop", bindingflags.instance | bindingflags.nonpublic);             console.writeline("onstopmethod null = " + (onstopmethod == null));              console.writeline("foreach service in service run count:" + servicestorun.count());             foreach (servicebase service in servicestorun)             {                 console.write("stopping {0}...", service.servicename);                 onstopmethod.invoke(service, null);                 console.writeline("stopped");             }              console.writeline("all services stopped.");             // keep console alive second allow user see message.             thread.sleep(1000);         }         #endregion     } } 

the issue happens when try call console.readkey(). program seems hang or exit extent. example, when run command prompt runs expected, shows "press key stop services , end process..." "before readkey". then, once hit [enter] console goes default command prompt. yet reason application still showing running in task manager. seems if it's getting hung up.

if change application type console application works expected , looks great. need build windows application. think issue using attachconsole(-1) not same building console application.

the credit on goes hans. i'm not sure why deleted answer wish not have.

basically command process , application fighting on command window (he said more elegantly i).

he suggested 1 of 2 things.

  1. create small app "my app name.com" separate app "my app name.exe" , let create new command window starting service.

  2. use windows start command run application instead of trying run normally.

i choose use ladder method. using wait switch forces command processor wait until application has finished until tries grab key presses again. take note of third param when running start. "" 2 double quotes pass blank param after /wait param. necessary in order pass params after application running.

before

c:\"my app name.exe" -service

after

c:\start /wait "" "my app name.exe" -service


Comments

Popular posts from this blog

sql - invalid in the select list because it is not contained in either an aggregate function -

Angularjs unit testing - ng-disabled not working when adding text to textarea -

How to start daemon on android by adb -