Best way to always keep console open [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Hello I wanted to know what is the best way to keep a console open forever? I want the fastest way, the most stable way, basically the best way to keep it open forever untill I close it.
I have recently been using the code below, but someone has said while loops are not good? or something like that, or storing stuff inside them isn't good? I basically just wanted your guys advice on what is the overall best way to do this? or a few of the best ways...
while (true) //in Program.cs in void Main
Console.ReadKey();

Do a simple Console Application and it will be open until the end of the execution. If you close the console you close the app. If you dont need the console it will remain open until the app is done running (so no loop or anything) and when you will be ready to use it, it will still be there waiting for you.
EDIT:
You might want to consider doing a Service application then. You wont have any console running and the application will be standing there behind and no one will see a black box and risk of closing it by mistake. You can then stop it with the Service Panel. The core of your service will be a simple thread waiting on a signal (a player connect). so your app run 24/7 without any problem and can be close easily.

I see no problem with a loop. I would have a command that can be input to close the window from a text input though. Something like:
string s = "";
while (s != "kill")
s = Console.ReadLine();
Some times while(true) loops can be dangerous because they will always run but I feel a while loop is fine. I have used this code for servers and the like. It has never been a problem for me.

So in your comment you say:
I want to keep it open 24/7 untill I hit "X"
In this case, do this:
Console.WriteLine("Press X to stop");
do
{
while (!Console.KeyAvailable)
{
// Do something
}
} while (Console.ReadKey(true).Key != ConsoleKey.X);
Console.WriteLine("Stopped");
As other people are pointing out, while(true) would be a performance hog.
Maybe (there is not enough info to know that) what you want to do as well is to start a thread before the loop, and kill it after the loop. This way your functions run parallel to the loop but you are in control of killing it whenever you want (pressing X). To do this in a clean way, follow the example at the bottom of the page.
...or by brute force:
Console.WriteLine("Running the process");
System.Threading.Thread workerThread = new System.Threading.Thread(MyFunction);
workerThread.Start();
Console.WriteLine("Press X to stop");
do
{
while (!Console.KeyAvailable)
{
// Do something
}
} while (Console.ReadKey(true).Key != ConsoleKey.X);
workerThread.Abort();
Console.WriteLine("Stopped");

Related

C# Updating log textbox while running

I have spent the past few days working on bot for an MMO. It runs in one big loop, with 1-2 other smaller loops inside. So far its going great. When its running it is set to update a richtextbox with what it is currently doing, just so I can easily troubleshoot later.
My problem is while its active and looping it does not auto update the textbox until it has finished everything it is doing. Which is hard when its set in an infinite loop. I would like to be able to run the bot with the main program window on the other monitor giving me updates as it goes along.
The whole program seems to freeze up and I cant interact with it at all while running. This also causes problems when I want it to stop. The only way I have of stopping it at the minute is to click Stop in visual studio.
I have tried searching around, but I have no idea what to search for. I hope I explained it well enough.
Thanks in advance.
This would be a nice read :
http://www.beingdeveloper.com/use-dispatcher-in-wpf-to-build-responsive-applications/
To summaries
You can send in a delegate fx, which is responsible for a formatter or writter. In you implemetation it would be the one which does AppendText. and make sure the Richtextbox.AppendText is within Dispatcher.Invoke()
Code Sample
class BotRand
{
//Write Event is delegate
public execute(WriteEvent writeFx)
{
//Crawl
writeFx("message");
}
}
class MainWindow : Window
{
void WriteFunc(object message, EventArgs outline)
{
Dispatcher.Invoke(new Action(() => richText.AppendText(message));
}
}
This should help you start your search more effectively.
Thanks,

SpeechSynthesizer.SpeakAsync method not immediately speaking

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.

Reading StandardInput stops code execution without breaking application

Im using Stockfish game engine to power Human Vs Computer games.
Here is first part of the code:
Process _proc= new Process();
_proc.StartInfo = new ProcessStartInfo(path);
_proc.StartInfo.RedirectStandardInput = true;
_proc.StartInfo.RedirectStandardOutput = true;
_proc.StartInfo.UseShellExecute = false;
_proc.StartInfo.CreateNoWindow = true;
_proc.Start();
_proc.StandardInput.WriteLine("uci");
_proc.StandardInput.WriteLine("ucinewgame");
At this point everything is ok, but when I try to read StandardOutput something weird happens.
string result = _proc.StandardOutput.ReadToEnd();
Stockfish.exe program pops-up my application is running but code after that line is not executing. When I press pause, it points at this line:
If I use:
while (!_proc.StandardOutput.EndOfStream)
{
result += _proc.StandardOutput.ReadLine();
}
Same thing happens only at while statement. result has its full value there, all the text is written into it.
Is there any way to overcome this without async reading?
Side problem:
Since this is all part of singleton class that is used over whole ASP.NET application, i dont feel like using async reading since Im not sure how can I protect (with locking) multiple threads writing into it. Also, I dont know how to stop current thread since the processing of command can last up to 10 sec.
I don't feel like using Thread.Sleep() to constantly check for end of reading output, not elegant.
Considering side problem, how could i avoid multithread problems if async is only solution?
My threading knowledge is weak, so please have that in mind when giving thread related answers. Thank you.
The call to StandardOutput.ReadToEnd will block until this process ends. Is the goal here to read, process, and respond to various text commands from the process you spawn as you receive them?
You must approach this via asynchronous reading.
For example, you could setup a listener to Process.OutputDataReceived. Then call Process.BeginOutputReadLine to start reading. Your code will continue execution. Meanwhile, the .NET Framework will handle incoming text messages on a separate thread.

Alternative to Console.ReadLine() to keep the Console visible

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.

Port scanning using threadpool

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.

Categories