Isn't there a better looking statement (or way) to keep the console from disappearing than the hackish Console.ReadLine() call. Something that's more expressive of the purpose of, more orthogonal to, keeping the Console visible ?
If you are still developing application you can run via Ctrl + F5 (Without debugging)
otherwise you can use Console.ReadKey() (same but there is no more option)
You can do:
Console.ReadKey();
Console.ReadLine() is not really hackish, your pausing the screen to wait for input. The input can either be a single key, or a string.
Update
One nice thing about the ReadKey() method is that it "waits, that is, blocks on the thread issuing the ReadKey method, until a character or function key is pressed." MSDN
This is different than ReadLine which takes in a string. Arguably, cleaner.
It depends on the context. If you're talking about running a command line, debugging through your code, and then being able to view the results on the console you have two options:
If you run with the debugger attached (f5), you must use Console.ReadLine
If you run without the debugger attached (ctrl + f5), it will stay open ... but then you obviously can't debug through.
I'm not sure why that's the default behavior, but there it is :-)
I usually use one of these:
Console.ReadKey(true); //You might want to put this in an infinite loop
new AutoResetEvent(false).WaitOne();
In VS You can also run (Ctrl + F5) the program (in distinction to running in debug) and it will add a system pause after it finishes executing.
I'd say that WaitOne, and just running (& not debugging) the program are your non-hackish options.
If you do want to debug, perhaps set a breakpoint at the last }.
Depends on what I am doing. If I am doing multi-threaded work and want my Console application to remain alive until all other work is done, I usually do something like this. (Similar to MasterMastic)
using System;
using System.Threading;
namespace Test_Console
{
class Program
{
static EventWaitHandle EWHandle;
static void Main(string[] args)
{
EWHandle = new EventWaitHandle(false, EventResetMode.AutoReset);
Thread WorkThread = new Thread(new ThreadStart(DoStuff));
EWHandle.WaitOne();
}
static void DoStuff()
{
Console.WriteLine("Do what you want here");
EWHandle.Set();
}
}
}
Of course, there's always just using the regular breakpoints and the other debugging tools if that's what you're going for.
Related
I have a c# program that I want to run multiple copies simultaneously. They need to communicate to each other; basically they'll run to a point then check if any other program has reached this point yet and, if not, set a flag telling the other programs to wait until the first process completes. Then the other programs try to "take control"; the first one wins and the process repeats.
Note that I don't have a "master" program; they're all the same.
Using a back-end database I think would be too slow. I've considered using Memory Mapped files, but I'm concerned about two programs reading it and seeing that it's OK to proceed, but then they'll both try to write to the file simultaneously and something will break. I only need a flag that the programs can check and, if false, set to true in the same code block.
Ideally the solution will run fast and be not too complex.
Any suggestions would be greatly appreciated. Thanks.
You can use a named mutex for this. These are very lightweight:
using System;
using System.Threading;
namespace Demo;
public static class Program
{
static void Main()
{
using var handle = new Mutex(initiallyOwned:false, "EventNameHere");
while (true)
{
Console.WriteLine("Obtaining lock.");
handle.WaitOne();
Console.WriteLine("Obtained lock. Simulating work");
Thread.Sleep(4000);
Console.WriteLine("Signalling lock.");
handle.ReleaseMutex();
}
}
}
Try running several instances of that console application and you'll see that only one is simulating the work at once.
Note that this sample code is very simplistic - in the real world you will have to manage how the application shuts down and stops waiting for the mutex in order to avoid AbandonedMutexException
When I run my program, the console window seems to run and close. How to keep it open so I can see the results?
class Program
{
public class StringAddString
{
public virtual void AddString()
{
var strings2 = new string[] { "1", "2", "3", "4", "5","6", "7", "8", "9"};
Console.WriteLine(strings2);
Console.ReadLine();
}
}
static void Main(string[] args)
{
StringAddString s = new StringAddString();
}
}
Put a Console.Read() as the last line in your program. That will prevent it from closing until you press a key
static void Main(string[] args)
{
StringAddString s = new StringAddString();
Console.Read();
}
If you want to keep it open when you are debugging, but still let it close normally when not debugging, you can do something like this:
if (System.Diagnostics.Debugger.IsAttached) Console.ReadLine();
Like other answers have stated, the call to Console.ReadLine() will keep the window open until enter is pressed, but Console.ReadLine() will only be called if the debugger is attached.
There are two ways I know of
1) Console.ReadLine() at the end of the program. Disadvantage, you have to change your code and have to remember to take it out
2) Run outside of the debugger CONTROL-F5 this opens a console window outside of visual studio and that window won't close when finished. Advantage, you don't have to change your code. Disadvantage, if there is an exception, it won't drop into the debugger (however when you do get exceptions, you can simply just rerun it in the debugger)
Console.ReadKey(true);
This command is a bit nicer than readline which passes only when you hit enter, and the true parameter also hides the ugly flashing cursor while reading the result :) then any keystroke terminates
You forgot calling your method:
static void Main(string[] args)
{
StringAddString s = new StringAddString();
s.AddString();
}
it should stop your console, but the result might not be what you expected, you should change your code a little bit:
Console.WriteLine(string.Join(",", strings2));
You can handle this without requiring a user input.
Step 1. Create a ManualRestEvent at the start of Main thread
ManualResetEvent manualResetEvent = new ManualResetEvent(false);
Step 2 . Wait ManualResetEvent
manualResetEvent.WaitOne();
Step 3.To Stop
manualResetEvent.Set();
Write Console.ReadKey(); in the last line of main() method. This line prevents finishing the console. I hope it would help you.
If your using Visual Studio just run the application with Crtl + F5 instead of F5. This will leave the console open when it's finished executing.
Use Console.Readline() at the end .Your code will not close until you close it manually.Since Readline waits for input that needs to be entered for your code hence your console will be open until you type some input.
For visual c# console Application use:
Console.ReadLine();
Console.Read();
Console.ReadKey(true);
for visual c++ win32 console application use:
system("pause");
press ctrl+f5 to run the application.
Make sure to useConsole.ReadLine();
to keep the preceeding Console.WriteLine(""); message from closing.
Console.Read()
-> Console stays open until you press a button on your keyboard
To be able to give it input without it closing as well you could enclose the code in a while loop
while (true)
{
<INSERT CODE HERE>
}
It will continue to halt at Console.ReadLine();, then do another loop when you input something.
If you're using Visual Studio, then the IDE has an option to keep the window open under
Tools > Options > Debugging >
Automatically close the console when debugging stops
Unlike CTRL + F5, this allows you to use breakpoints while debugging.
I am trying to use the SpeakAsync() method to speak some text. However, it doesn't start speaking anything until I call Speak(). I don't want to call Speak(). If I remove the Speak() method from this code nothing gets called at all:
using (SpeechSynthesizer synth = new SpeechSynthesizer())
{
synth.SelectVoice("ScanSoft Emily_Dri20_22kHz");
synth.Rate = 10;
synth.Volume = 100;
synth.SpeakAsync("oh, i'm a lumberjack and i'm okay! I sleep all night and I work all day!");
synth.SpeakAsync("If he was dying he wouldn't bother writing ah! He'd just say it!");
synth.Speak("i don't want to go on the cart.");
synth.SpeakAsync("We don't have a lord. We're an anarcho-syndicalist commune.");
synth.SpeakAsync("If you do not show us the grail, we shall take your castle by force!");
synth.Speak("what do you mean, an african swallow or a european swallow?");
UPDATE:
It appears other people are having this problem but no solution has been found yet:
other people having this problem
It's because Speak is a blocking call which keeps the program running. Since you're running this as a console application add Console.ReadKey(); at the end of your code to ensure that the application remains running until the user presses a key.
Otherwise, the main thread will exit because SpeakAsync returns immediately so your program is flying through all those lines and then exiting which is why you don't hear anything.
Update based on comments -
The using block is disposing the SpeechSynthesizer almost immediately which is why nothing can be heard. You can either place Console.ReadKey(); just before the closing brace of the using block or remove the using block and dispose of it manually later on.
I am trying to run a small app that scans ports and checks to see if they are open using and practicing with threadpools. The console window will ask a number and scans ports from 1 to X and will display each port whether they are open or closed. My problem is that as it goes through each port, it sometimes stops prematurely. It doesn't stop at just one number either, its pretty random. For example it I specify 200. The console will scroll through each port then stops at 110. Next time I run it, it stops at 80.
Code
Left out some of the things, assume all variables are declared where they should. First part is in Main.
static void Main(string[] args)
{
string portNum;
int convertedNum;
Console.WriteLine("Scanning ports 1-X");
portNum = Console.ReadLine();
convertedNum = Convert.ToInt32(portNum);
try
{
for (int i = 1; i <= convertedNum; i++)
{
ThreadPool.QueueUserWorkItem(scanPort, i);
Thread.Sleep(100);
}
}
catch (Exception e)
{
Console.WriteLine("exception " + e);
}
}
static void scanPort(object o)
{
TcpClient scanner = new TcpClient();
try
{
scanner.Connect("127.0.0.1",(int)o);
Console.WriteLine("Port {0} open", o);
}
catch
{
Console.WriteLine("Port {0} closed",o);
}
}
}
If this is the entire code, then the error is probably caused by you just falling through to the end of main() without waiting for all your thread pool threads to finish. The ThreadPool threads are all aborted once your main thread exits after falling through main().
Try removing the Thread.Sleep(100) (it is not needed, this is the wrong way, you'd never know for how long to sleep for and it partially defeats the purpose of using a ThreadPool in the first place) and you will probably not even check a single port!
Instead you could have each of your worker threads set an event and use WaitAll in main for all events to finish. See http://msdn.microsoft.com/en-us/library/3dasc8as.aspx for an example.
Edit:
Thinking this through, the solution referenced at the link above is probably less than ideal for you as well (it might involve having to allocate an array of 65000 events, this would be excessive). In .net 4 you could use a CountdownEvent like this:
Sorry, I gotta run, but check this example http://msdn.microsoft.com/en-us/library/system.threading.countdownevent.aspx and let us know when you have further questions, I'm sure someone can and will elaborate or suggest a better solution and a solution more suitable for .net3
What OS? Don't forget, different versions of XP have tcp connection limits, while you may also be triggering anti DDOS protection as well.
Also, your logic is flawed. Just because TcpClient.Connect excepted, doesn't mean the port is closed. You should be capturing and displaying that exception's details as I imagine it will offer you greater insight into why your code is stopping. Keep in mind, its possible to throw a SocketException or SecurityException as well.
Concerning the threading part, you could consider using the Task Parallel Library (TPL) instead of directly accessing the ThreadPool.
IMHO it offers a more simple use and a more intuitive/readable syntax.
Hey I am fairly new to the c# programming language and have enjoyed my experience so far. I normally develop applications in java but a need for the win32 library has lead me to c# so far the languages seem relatively similar. however a problem I am having at the moment is a simple piece of code that can be best explained in this example
I am trying to print a piece of string to console then display the windows form then print another piece of string to console. however the result i get is first string is printed then the form is displayed, i then have to close the form before the last string is printed. the question i would like to ask is is there anyway to get this working so the second print to console is displayed immediately after the form is displayed. im guessing it has something to do with threading but I am not entirely sure how to implement this
The solution is quite simple:
Just create a Windows Forms Application (when creating the project - which you probably did) and then go to Properties (in context menu "Project", it's the last item) and set "Output type" to "Console Application". The forms will work as before and furthermore the application will now open the console too. You can then freely write to or read from the console.
static class Program
{
[STAThread]
static void Main()
{
Console.WriteLine("first string");
var form = new Form1();
form.Show();
Console.WriteLine("the second string");
Application.Run();
}
}
It sounds like you want to be able to output messages to the console while the form is being displayed, correct? The basic issue is that as long as the form is visible, there must be a message loop running, handling events for the form. The message loop is inside Application.Run, so once you call it, it won't return until the form is closed (as you discovered).
So if you want to write to the console while the form is visible, you have a couple of options. One, as you mentioned, is to use multiple threads. Let your main thread run the message loop, and start up a second thread to write to the console. But that's not necessary--you can also write to the console from within an event handler, directly or indirectly. There's nothing wrong with doing a Console.WriteLine from within a button click handler. Or you can have your button handler call a method in your Program class, and do the writing there.
As for which solution is better, it would help to know more about what you're trying to accomplish. I assume that you don't just want to write stuff to the console--what else is it that you want to do while the form is being displayed?
My suggestion would be to start with a Console application. You can always open a WinForm from a console application...which would give you exactly what you're looking for. (you might want to think about multi-threading as well.
Hey everyone thanks for your answers I made some progress with what im trying to achieve but im not sure how correct or thread safe it is here is the code i got to run
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace Project1
{
class Class2
{
[STAThread]
static void Main()
{
Console.WriteLine("hello");
Class2 t = new Class2();
t.test();
Console.WriteLine("second string");
}
public void test()
{
Thread t = new Thread(new ThreadStart(StartNewStaThrea));
t.Start();
}
private void StartNewStaThrea()
{
Application.Run(new Form1());
}
}
}
pls let me know what you think of this solution
I know this is a super-old question, but I'm going to answer in hopes of karma. One interesting work-around that works well for this comes up if you're using Visual Studio (which is a fairly safe assumption). If you start a forms project in C# in Visual Studio, then make your appropriate forms, but then change the project type to a console application (by right clicking the project-->properties-->Console Application), it will still spawn your forms, but will also keep a Console open, now all you need to do is put one Console.Write statement before your form is created, and the other after, and maybe add a flush statement!
are you using form.showDialog() or form.show()?
form.showDialog() will block until the form is closed, while form.show() will not.
I would either start with a console app, and run the application from the static main function. This is from memory - I haven't had to mess with Winforms for years:
[STAThread]
static void Main()
{
Application.Run(new YourMainForm());
}
or
I would redirect Console.Out and shove that stream into a some sort of control like a text box or list box. This is a lot of code but doable... I have written this before for on-site debugging but don't have the code handy.
Why don't you just create a new windows form with multiline textbox and dock it to the form, set BackColor as Black ForeColor as White and create a public method to send text to that textBox.
If your aim is a one Form application this works pretty much brilliantly.