A question about a while (true) loop

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Jason (Kusanagihk)

    #1

    A question about a while (true) loop

    To all,

    I have written a SerialPort class / application using C# and .Net
    Framework 3.0.
    but I have a question; since my serialPort class / application is not
    a Windows Form application (rather it is just a console program);
    therefore I need a way to make the application "alive" until I kill
    the application or enter a "quit" signal through the serial port.

    I have tried the simplest way to make the app "alive" by using a
    "while (true)" loop; but of course, the result is not good since a
    "while(true )" loop will consume 100% cpu processing and slow down the
    PC too.

    So are there any other ways to keep a console app "alive" and not
    consuming the cpu 100%? I am thinking if a Thread might help, but I
    have no idea how... Also I was thinking, there must be some techniques
    to make an app "alive" and won't consume cpu time just like a Windows
    Form did (ie. it only consumes cpu processing power when there are any
    user events or system events)

    Any help would be appreciated :-)

    From Jason (Kusanagihk)
  • Kerem Gümrükcü

    #2
    Re: A question about a while (true) loop

    Hi Jason,

    you should work with synchronozation objects and functions
    like WaitForSingleOb ject to block your applications execution
    without affecting the overall operating system. See here:

    [WaitForSingleOb ject (kernel32)]

    Comes woth a little but good example how this works!

    MSDN[WaitForSingleOb ject]
    http://msdn2.microsoft.com/en-us/library/ms687032.aspx


    See all the information for syncronization and its functions
    and how this stuff works for more and detailed information:

    Regards

    Kerem

    --
    -----------------------
    Beste Grüsse / Best regards / Votre bien devoue
    Kerem Gümrükcü
    Microsoft Live Space: http://kerem-g.spaces.live.com/
    Latest Open-Source Projects: http://entwicklung.junetz.de
    -----------------------
    "This reply is provided as is, without warranty express or implied."


    Comment

    • Nicholas Paldino [.NET/C# MVP]

      #3
      Re: A question about a while (true) loop

      Jason,

      I'm assuming you haven't written a new SerialPort class, but rather, are
      using the class in the System.IO.Ports namespace.

      Do you need to gather input during this process, or is your application
      strictly showing output? If it is strictly showing output, then perhaps you
      should go from an event-based model to a pull model, where you query the
      port for the data you need, and output it. This will keep your app alive.

      If you wish to stay with the event-based model, then you could always
      just stick perform a loop with a Console.ReadLin e in it. You could ignore
      the input, or process it as appropriate, exiting the loop when you determine
      the time is right.


      --
      - Nicholas Paldino [.NET/C# MVP]
      - mvp@spam.guard. caspershouse.co m

      "Jason (Kusanagihk)" <kusanagihk@gma il.comwrote in message
      news:11766e6d-5394-486d-9b47-2af05eae9f9e@b4 0g2000prf.googl egroups.com...
      To all,
      >
      I have written a SerialPort class / application using C# and .Net
      Framework 3.0.
      but I have a question; since my serialPort class / application is not
      a Windows Form application (rather it is just a console program);
      therefore I need a way to make the application "alive" until I kill
      the application or enter a "quit" signal through the serial port.
      >
      I have tried the simplest way to make the app "alive" by using a
      "while (true)" loop; but of course, the result is not good since a
      "while(true )" loop will consume 100% cpu processing and slow down the
      PC too.
      >
      So are there any other ways to keep a console app "alive" and not
      consuming the cpu 100%? I am thinking if a Thread might help, but I
      have no idea how... Also I was thinking, there must be some techniques
      to make an app "alive" and won't consume cpu time just like a Windows
      Form did (ie. it only consumes cpu processing power when there are any
      user events or system events)
      >
      Any help would be appreciated :-)
      >
      From Jason (Kusanagihk)

      Comment

      • Mr. Arnold

        #4
        Re: A question about a while (true) loop


        "Jason (Kusanagihk)" <kusanagihk@gma il.comwrote in message
        news:11766e6d-5394-486d-9b47-2af05eae9f9e@b4 0g2000prf.googl egroups.com...
        To all,
        >
        I have written a SerialPort class / application using C# and .Net
        Framework 3.0.
        but I have a question; since my serialPort class / application is not
        a Windows Form application (rather it is just a console program);
        therefore I need a way to make the application "alive" until I kill
        the application or enter a "quit" signal through the serial port.
        >
        I have tried the simplest way to make the app "alive" by using a
        "while (true)" loop; but of course, the result is not good since a
        "while(true )" loop will consume 100% cpu processing and slow down the
        PC too.
        >
        So are there any other ways to keep a console app "alive" and not
        consuming the cpu 100%? I am thinking if a Thread might help, but I
        have no idea how... Also I was thinking, there must be some techniques
        to make an app "alive" and won't consume cpu time just like a Windows
        Form did (ie. it only consumes cpu processing power when there are any
        user events or system events)
        >
        Any help would be appreciated :-)
        Why can't you put the application to sleep by using the
        Thread.Sleep(wa ittime) or using a Timer with an Timer Elapsed time event?

        Comment

        • Kerem Gümrükcü

          #5
          Re: A question about a while (true) loop

          Hi Nicholas,

          good reasons not to pinvoke native synchronization methods
          from the windows api. Worked good for me until today. So my
          sugesstion was very wrong, i will never use that again. Thats
          the price you pay, when you come from Asm/C Programming of
          the Windows and you are used to use Windows API. You
          always try to solve the problem using the Native or Usermode
          API from Windows.


          Regards

          Kerem


          --
          -----------------------
          Beste Grüsse / Best regards / Votre bien devoue
          Kerem Gümrükcü
          Microsoft Live Space: http://kerem-g.spaces.live.com/
          Latest Open-Source Projects: http://entwicklung.junetz.de
          -----------------------
          "This reply is provided as is, without warranty express or implied."


          Comment

          • Ben Voigt [C++ MVP]

            #6
            Re: A question about a while (true) loop


            "Kerem Gümrükcü" <kareem114@hotm ail.comwrote in message
            news:OP%23O7SDN IHA.4948@TK2MSF TNGP02.phx.gbl. ..
            Hi Nicholas,
            >
            good reasons not to pinvoke native synchronization methods
            from the windows api. Worked good for me until today. So my
            sugesstion was very wrong, i will never use that again. Thats
            the price you pay, when you come from Asm/C Programming of
            the Windows and you are used to use Windows API. You
            always try to solve the problem using the Native or Usermode
            API from Windows.
            "never use that again" seems a bit extreme. You just have to be somewhat
            careful, i.e. use .NET wait routines in threads with .NET components and
            controls, and OS wait routines in purely native threads. (Ok, if your
            program is 100% C# you probably don't have any purely native threads).

            Using only .NET wait routines just isn't a viable option until .NET gets an
            alertable wait.


            Comment

            • Arnshea

              #7
              Re: A question about a while (true) loop

              On Dec 3, 11:35 am, "Ben Voigt [C++ MVP]" <r...@nospam.no spamwrote:
              "Kerem Gümrükcü" <kareem...@hotm ail.comwrote in message
              >
              news:OP%23O7SDN IHA.4948@TK2MSF TNGP02.phx.gbl. ..
              >
              Hi Nicholas,
              >
              good reasons not to pinvoke native synchronization methods
              from the windows api. Worked good for me until today. So my
              sugesstion was very wrong, i will never use that again. Thats
              the price you pay, when you come from Asm/C Programming of
              the Windows and you are used to use Windows API. You
              always try to solve the problem using the Native or Usermode
              API from Windows.
              >
              "never use that again" seems a bit extreme. You just have to be somewhat
              careful, i.e. use .NET wait routines in threads with .NET components and
              controls, and OS wait routines in purely native threads. (Ok, if your
              program is 100% C# you probably don't have any purely native threads).
              >
              Using only .NET wait routines just isn't a viable option until .NET gets an
              alertable wait.
              I wonder if there are any managed methods that are implemented via
              APC? Such that there would be a need for a managed thread to be able
              to indicate that it's alertable? Doesn't the .net ThreadPool satisfy
              a similar purpose wrt asynchronous execution in a managed context?

              I've never (knowingly) had occasion to use QueueUserAPC() in the
              native world; what are some scenarios where it might be used?

              Comment

              • Ben Voigt [C++ MVP]

                #8
                Re: A question about a while (true) loop

                >Using only .NET wait routines just isn't a viable option until .NET gets
                >an
                >alertable wait.
                >
                >I wonder if there are any managed methods that are implemented via
                >APC? Such that there would be a need for a managed thread to be able
                >to indicate that it's alertable? Doesn't the .net ThreadPool satisfy
                >a similar purpose wrt asynchronous execution in a managed context?
                >
                >I've never (knowingly) had occasion to use QueueUserAPC() in the
                >native world; what are some scenarios where it might be used?
                I think .NET provides classes for the case of user work items as you said,
                I've only been using I/O APCs (ReadFileEx and WriteFileEx, WSARecvMsg and
                WSASend, and I think IOCTLs can do completion routines as well using
                NtDeviceIoContr olFile). The .NET I/O APIs are extremely file-centric, the
                SerialPort class is for example totally unusable for me for a number of
                reasons.

                For I/O, APCs are very nice -- the interface is very clean, and there's
                virtually no need for shared data (no master list of all event handles or
                completion ports).

                I just didn't see any way to get Win32 I/O to play well in a managed thread,
                because I can't control the message dispatch loop. Plus with a high
                priority native thread dedicated to I/O and lockless queues for passing work
                items back to .NET, I get much more accurate timestamps on incoming data.
                C++/CLI is great for this low-level work, then all the UI and so forth done
                in C#.


                Comment

                • Arnshea

                  #9
                  Re: A question about a while (true) loop

                  On Dec 3, 2:58 pm, "Ben Voigt [C++ MVP]" <r...@nospam.no spamwrote:
                  >
                  For I/O, APCs are very nice -- the interface is very clean, and there's
                  virtually no need for shared data (no master list of all event handles or
                  completion ports).
                  >
                  I just didn't see any way to get Win32 I/O to play well in a managed thread,
                  because I can't control the message dispatch loop. Plus with a high
                  priority native thread dedicated to I/O and lockless queues for passing work
                  items back to .NET, I get much more accurate timestamps on incoming data.
                  C++/CLI is great for this low-level work, then all the UI and so forth done
                  in C#.
                  *whistle* - very nice indeed.

                  Comment

                  • Jason (Kusanagihk)

                    #10
                    Re: A question about a while (true) loop

                    Nicholas,

                    Ya right, I'm using the SerialPort class from the .Net Framework; and
                    my application would need to handle both input /output of serial
                    signals.

                    So I have found a ReadByte method in the SerialPort class (from .Net
                    Framework); so if this method blocks ... then I guess the app could
                    survive... the following is my idea, please comment :-)

                    eg. (the pull model.... )
                    while (true)
                    {
                    // if this method blocks...
                    mSerialPort.Rea dByte (byteArray, 0, 64);

                    // data received --perform the data resolving logic (etc)
                    ...

                    // if data received is a token/identifier --"EXIT", then exit the
                    loop
                    if (new String(byteArra y).equals("EXIT "))
                    {
                    // any code cleanup or final processings...
                    ...
                    break;
                    }
                    }

                    PS. At the moment, my SerialPortApp class is just a generic class type
                    -- which could/should be used by either a Console App or Windows Form
                    app later on.

                    Comment

                    • Ben Voigt [C++ MVP]

                      #11
                      Re: A question about a while (true) loop


                      "Jason (Kusanagihk)" <kusanagihk@gma il.comwrote in message
                      news:bdbbdf07-c068-4f07-b29f-41ebdc5236ea@i2 9g2000prf.googl egroups.com...
                      Nicholas,
                      >
                      Ya right, I'm using the SerialPort class from the .Net Framework; and
                      my application would need to handle both input /output of serial
                      signals.
                      >
                      So I have found a ReadByte method in the SerialPort class (from .Net
                      Framework); so if this method blocks ... then I guess the app could
                      survive... the following is my idea, please comment :-)
                      It should more-or-less work. You need to run a loop like that in a
                      background thread so it doesn't lock up your entire application. Also, I'd
                      prefer using the "return" statement instead of "break" to exit the loop,
                      because "break" is more likely to change meaning if you add a switch or
                      nested loop. Your exit test needs some work as well, but the overall idea
                      should work.
                      >
                      eg. (the pull model.... )
                      while (true)
                      {
                      // if this method blocks...
                      mSerialPort.Rea dByte (byteArray, 0, 64);
                      >
                      // data received --perform the data resolving logic (etc)
                      ...
                      >
                      // if data received is a token/identifier --"EXIT", then exit the
                      loop
                      if (new String(byteArra y).equals("EXIT "))
                      {
                      // any code cleanup or final processings...
                      ...
                      break;
                      }
                      }
                      >
                      PS. At the moment, my SerialPortApp class is just a generic class type
                      -- which could/should be used by either a Console App or Windows Form
                      app later on.

                      Comment

                      Working...