Detect if compiling as a console application

  • Thread starter Thread starter Michael D. Ober
  • Start date Start date
M

Michael D. Ober

Is there anyway the VB Compiler can detect if a program is a console
application? I have some libraries that need to write to the console if
the program is a console app.

Thanks,
Mike Ober.
 
can't you just call System.Console.WriteLine("") anyway? If the app is
a console app, the line will be written to it, otherwise they will not.
 
What Chris describes is my experience. I use it alot for throwing
stuff to console that helps me debug. There is a noticable performance
hit though, and I wonder, if the console is not enabled, and a
Console.WriteLine call is made, what happens? Is there some sort of
buffer or resource that the text still writes to? I've never tested
the performance of writing to console when there is no console, as I
only do this when compiled as DEBUG, using conditional compilation
statements.
 
What Chris describes is my experience. I use it alot for throwing
stuff to console that helps me debug. There is a noticable performance
hit though, and I wonder, if the console is not enabled, and a
Console.WriteLine call is made, what happens? Is there some sort of
buffer or resource that the text still writes to? I've never tested
the performance of writing to console when there is no console, as I
only do this when compiled as DEBUG, using conditional compilation
statements.

Maybe System.Windows.Forms.Application.MessageLoop will help decide the
issue at runtime. It returns true if there a message loop is running on the
current thread. So, if your app is single threaded, then it should tell the
difference between a console app and a windows app. Multi-threading
complicates things - a worker thread in a windows app cant effectively use
it. Also, I don't know what it does in other settings, eg a service.

The compiler /target option is what really decides the issue. So the answer
to the original question is yes - the compiler knows about /target. But I
couldn't find out how to access it or an equivalent at compile time (eg via
#if) or run time.
 
You get an IOException error if you don't have a console. My current
workaround is as follows:

public sub WriteLog(byval msg as string)
static isConsole as boolean = true
debug.print(msg)
logs.WriteLog(msg) ' Logs is always declared and ready to use
if not isConsole then return
try
Console.Writeline(msg)
catch ex as exception
isConsole = false
end try
end sub

Still a small performance hit (testing a local static variable), but not the
major performance hit everytime it's called.

Mike.
 
Back
Top