A question about a while (true) loop

  • Thread starter Jason (Kusanagihk)
  • Start date
J

Jason (Kusanagihk)

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)
 
K

Kerem Gümrükcü

Hi Jason,

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

[WaitForSingleObject (kernel32)]
http://pinvoke.net/default.aspx/kernel32/WaitForSingleObject.html
Comes woth a little but good example how this works!

MSDN[WaitForSingleObject]
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

--
 
N

Nicholas Paldino [.NET/C# MVP]

Using these, as opposed to the options in the framework (the Mutex
class, the event classes, the Semaphore classes) are a pretty bad idea. The
CLR does some extra work when it comes across synchronization handles in
order to allow things like the Thread class to still be able to kill a
thread, do pumping on for COM apartments, etc, etc.

It's detailed in Chris Brumme blog here:

http://blogs.msdn.com/cbrumme/archive/2003/04/17/51361.aspx

If you have a synchronization handle which isn't represented in the
framework which you can call WaitForSingleObject, etc, etc, on, you should
create a class derived from WaitHandle and use that, as the WaitOne
overloads will eventually call this method, but set things up so the CLR can
make all of it's guarantees when it comes to blocking.
 
N

Nicholas Paldino [.NET/C# MVP]

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.ReadLine in it. You could ignore
the input, or process it as appropriate, exiting the loop when you determine
the time is right.
 
M

Mr. Arnold

Jason (Kusanagihk) said:
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(waittime) or using a Timer with an Timer Elapsed time event?
 
K

Kerem Gümrükcü

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


--
 
B

Ben Voigt [C++ MVP]

Kerem Gümrükcü said:
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.
 
A

Arnshea

"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?
 
B

Ben Voigt [C++ MVP]

Using only .NET wait routines just isn't a viable option until .NET gets
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
NtDeviceIoControlFile). 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#.
 
A

Arnshea

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.
 
J

Jason (Kusanagihk)

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.ReadByte (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(byteArray).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.
 
B

Ben Voigt [C++ MVP]

Jason (Kusanagihk) said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top