C# Pause one console application when other console application starts - c#

I have one console application for testing purposes like following:
static void Main(string[] args)
{
do
{
for (int i = 0; i < 10000000; i++)
{
Console.WriteLine("Doing some endless loop");
Console.WriteLine(i.ToString());
}
} while (true);
}
As you can see the code is very basic, and I've set it up to endless loop in order to test what I would like to achieve.
The other console application is called "Updater" and I would like to to pause the "EndlessLoop" console application once the "Updater" application is started.
Does anyone knows if this is doable in c# .NET?

public static bool IsAppRunning()
{
foreach (Process process in Process.GetProcesses())
{
if (process.ProcessName.Contains("Updater"))
{
return true;
}
}
return false;
}
If you call this in while loop it tells you if Updater is running or not.

Not easy to communicate between 2 application
One proposition: When your console Updater starts, you create a file in folder C:\Temps\token.txt. Then, if your console EndlessLoop detects a file names token.txt in C:\Temps, you pause EndlessLoop

Related

Passing info from one console application to another using Arguments

I am not sure why this does not work. I have two applications one is the main application the second is called upon when needed to perform a task. to simplify I am taking out all the other code as I just need help with this one task
Console Application 1
static void Main()
{
ProcessStartInfo startinfo = new ProcessStartInfo();
startinfo.FileName = #"C:\ConsoleApp2.application";
startinfo.Arguments = "DateRange ClinetID PhoneNo";
Process.Start(startinfo);
}
Console Application 2
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Received the following arguments:\n" + args.Length);
for (var i = 0; i < args.Length; i++)
{
Console.WriteLine($"[{i}] = {args[i]}");
}
Console.WriteLine("\nPress any key to exit");
Console.ReadLine();
}
}
When I run this code the second application will open fine, however, the args.length is always 0. Any help would be great.
You seem to be in some misunderstanding, are you sure it's not .exe?
Two .Net Framework 4.8 Console Apps were created in the vs 2022 community, which can run correctly as shown in the figure.
If you have questions, please comment below.

How to re-start a console application if it crashes?

I have created a console application in C#. How can I program this application so that it will re-start itself after a crash?
If I understand your question correctly, you want to attempt to re-start a console app in the event of a crash. In C# console-apps the method defined as the entry point (usually static void main) is the root of the call stacks in the app. You essentially would need to call that method recursively. You will want to make sure that the app eventually fails if it is in some unintended or unrecoverable state.
For example in the main class:
static int retryCount;
const int numberOfRetries = 3;
static void Main(string[] args)
{
try
{
var theApp = new MyApplicationType(args);
theApp.StartMyAppLogic();
}
catch (ExpectedExceptionType expectThisTypeOfException)
{
thisMethodHandlesExceptions(expectThisTypeOfException);
}
catch (AnotherExpectedExceptionType alsoExpectThisTypeOfException)
{
thisMethodHandlesExceptions(alsoExpectThisTypeOfException);
}
catch (Exception unexpectedException)
{
if(retryCount < numberOfRetries)
{
retryCount++;
Main(args);
}
else
{
throw;
}
}
}
You can use a watchdog to process your monitor and restart it if crashed:
see: What's the best way to watchdog a desktop application?
You can use a windows service instead and set it's recovery options as indicated here: https://serverfault.com/questions/48600/how-can-i-automatically-restart-a-windows-service-if-it-crashes
You can use a scheduled task in task manager to start your application periodically , and set it to only start if previous run has ended:
https://support.microsoft.com/en-us/kb/323527
You could try something like this:
static void Main(string[] args)
{
try
{
// Application code goes here
}
catch (Exception)
{
var applicationPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
Process.Start(applicationPath);
Environment.Exit(Environment.ExitCode);
}
}
Basically, wrap all the code in a try/catch, and if any exceptions occur, the program will retrieve the .exe location with System.Reflection.Assembly.GetExecutingAssembly().Location; and then call Process.Start to run the application again.
You should control your console app from another application (watchdog, sheduler, procmon, servman, ...).
E.g. you can create your console app as a service and control it from service manager.

C# Console application read/writes on standard IO doesn't works

Have C# Console application which read/writes on standard input and output.
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Console application");
while(true)
{
int input = Console.Read();
Console.WriteLine(input.ToString());
}
}
}
I have other native application which launch above console application and read/writes with help of pipe communication.
C# console application writes are read successfully in external application and also initial writes from external application works fine and then it loops to read from the C# console application.
After that writes from external application on the pipe doesn't work.
Absurd thing is problem is happening on some of the operating system and few it is working fine.
C# Console application compile with .NET Framework 4 / Client Profile.
Known issue from MS :
http://support.microsoft.com/en-us/kb/2675468
Please check the KB for more details along with sample provided.
Try
static void Main(string[] args)
{
Console.SetIn(new StreamReader(Console.OpenStandardInput()));
while (Console.In.Peek() != -1)
{
string input = Console.In.ReadLine();
Console.WriteLine(input);
}
}
Does it work that way?
EDIT: I have updated my answer.
Sample usage/output:
dir /B | ConsoleApplication1.exe
produces:
ConsoleApplication1.exe
ConsoleApplication1.exe.config
ConsoleApplication1.pdb
ConsoleApplication1.vshost.exe
ConsoleApplication1.vshost.exe.config
ConsoleApplication1.vshost.exe.manifest
When I try your original code, it ends up spamming -1 constantly.
You can also try:
while (true)
{
int input = Console.Read();
if (input != -1) { // -1 = no input
Console.WriteLine(input.ToString());
}
}
Now it handles every character separately.

Output message to Console window if command line parameters incorrect

Can anyone help me output a message to a console box when my .exe is called with the wrong parameters?
Yesterday, some very kind people helped me work out how to call my app without a UI
Here is the thread
command line to make winforms run without UI
So, I have told my app to respond to "/silent archive=true transcode=true" and runs without a UI. Great!
Is it possible to output a message to the command window if they get the command incorrect?
as in "Parameters must be specified like this: /silent archive=true transcode=true"
I have tried this but nothing displays in the dos window..
static void Main(string[] args)
{
if (args.Length > 0)
{
if (args[0] == "/silent")
{
bool archive = false;
bool transcode = false;
try
{
if (args[1] == "transcode=true") { transcode = true; };
if (args[2] == "archive=true") { archive = true; };
Citrix_API_Tool.Engine.DownloadFiles(transcode, archive);
}
catch
{
Console.Write ("Hello");
Console.ReadLine();
return;
}
}
}
else
internal sealed class Program
{
[DllImport("kernel32.dll")]
private static extern bool AttachConsole(int dwProcessId);
private const int ATTACH_PARENT_PROCESS = -1;
[STAThread]
private static void Main(string[] args)
{
if(false)//This would be the run-silent check.
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
try
{
throw new Exception("Always throw, as this tests exception handling.");
}
catch(Exception e)
{
if(AttachConsole(ATTACH_PARENT_PROCESS))
{
//Note, we write to Console.Error, not Console.Out
//Partly because that's what error is for.
//Mainly so if our output were being redirected into a file,
//We'd write to console instead of there.
//Likewise, if error is redirected to some logger or something
//That's where we should write.
Console.Error.WriteLine();//Write blank line because of issue described below
Console.Error.WriteLine(e.Message);
Console.Error.WriteLine();//Write blank line because of issue described below
}
else
{
//Failed to attach - not opened from console, or console closed.
//do something else.
}
}
}
}
A problem is that the console would have already returned to taking input from the user. Hence you really want to try to have your exception as fast as you can if you're going to have it, so a fast validation check rather than an exception that might happen down the line, is preferable.

C# console application timer issue

I have a console applciation which is invoked by a Windows Service. This console application creates instances of System.Timers.Timer based on certain App.config file entries (I have created a custom App.config section and the number of timer instances will be same as that of the elements in this section). The console application is expected not to close - if it closes for some reason, the windows service will invoke it again.
To make the console application live for ever, I have an infinite loop written as the last statement of the console application. while (1 == 1) { }.
The issue is, I see that the console application terminates every 5 minutes. I don't understand why is this happening.
If there are any better approaches, please suggest.
Code
static void Main(string[] args)
{
Boolean _isNotRunning;
using (Mutex _mutex = new Mutex(true, _mutexID, out _isNotRunning))
{
if (_isNotRunning)
{
new ProcessScheduler().InitializeTimers();
while (1 == 1) { }
}
else
{
return;
}
}
public class ProcessScheduler
{
public void InitializeTimers()
{
XYZConfigSection.XYZAppSection section = (XYZConfigSection.XYZAppSection)ConfigurationManager.GetSection("XYZApp");
if (section != null)
{
XYZComponentTimer XYZComponentTimer = null;
for (int intCount = 0; intCount < section.XYZComponents.Count; intCount++)
{
XYZComponentTimer = new XYZComponentTimer();
XYZComponentTimer.ComponentId = section.XYZComponents[intCount].ComponentId;
XYZComponentTimer.Interval = int.Parse(section.XYZComponents[intCount].Interval);
XYZComponentTimer.Elapsed += new ElapsedEventHandler(XYZComponentTimer_Elapsed);
XYZComponentTimer.Enabled = true;
}
}
}
}
public class XYZComponentTimer:Timer
{
public string ComponentId { get; set; }
}
Update:
As mentioned in the code, the timer interval for each instance is set based on the config file values for corresponding element. Right now, there are two sections in the config file: one has an interval of 15 seconds, and another one 10 seconds.
Let me guess: The timer interval is 5min and the timer crashes causing the process to exit.
Why don't you log any crashes or attach a debugger?
Handle the AppDomain.UnhandledException event and log the exception.
Mutex was getting instantiated every 5 minutes for some weird reason, and was setting _isNotRunning to true. That was the issue.

Categories