C# Crash not caught by Debugger - c#

I have a pretty large project that just recently started crashing on exit. I am not the greatest C# coder but everything generally works as intended. In this case however, when I close my console application, it crashes but is not caught by the MSVC Debugger.
1) When I build it in Release and run it, it generally always crashes when I exit.
2) When I build it in Debug and run it, it seems to only crash on exit every 1 out of 3-5 times.
I did manage to get the error though when it didn't exit properly, but unfortunately the Exit Code doesn't match anything I can find online.
The program '[11108] MCDaemon.vshost.exe: Managed (v4.0.30319)' has exited with code -1073741510 (0xc000013a).
From what I have read on other people's questions, this is generally caused by Unmanaged Code acting up. Is there any way I can actually find out what the issue is short of a massive amounts of debug lines?
EDIT
From an answer below, this is the code causing the Exit code, but I don't really see anything issue with it.
public static Boolean Handler(MyWin32.CtrlTypes CtrlType)
{
// A switch to handle the event type.
switch (CtrlType)
{
case MyWin32.CtrlTypes.CTRL_C_EVENT:
Program.TerminateProcess();
break;
case MyWin32.CtrlTypes.CTRL_CLOSE_EVENT:
Program.TerminateProcess();
break;
}
return true;
}
public static void TerminateProcess()
{
// Stop the Poll Timer from Running
PollTimer.Stop();
log.LogMessage("Process is being Shutdown.");
log.LogMessage("Requesting Process to Stop....");
SendProcessCmd("stop");
// Wait and make sure it has exited
Thread.Sleep(5000);
if (!myProcess.HasExited)
{
log.LogMessage("My Process did not stop on its own, forcing Process to quit.");
myProcess.Kill();
}
log.LogMessage("My Process has been Shutdown.");
}

// Wait and make sure it has exited
Thread.Sleep(5000);
That's the problem statement. You are pinvoking SetConsoleCtrlHandler() in your code to get your Handler method called. Windows requires the control handler to be responsive and not take too long to return from the callback. The timeout for the CTRL_CLOSE_EVENT is exactly 5 seconds, explaining why it sometimes works. If it takes longer then Windows pulls the plug on the process.
You'll need to implement TerminateProcess differently. Killing a process is fairly arbitrary, you ought to be better off just not doing this. Or start another guard process. I can't make that call though.

0xC000013A: The application terminated as a result of a Ctrl+C.
This is because you closed the console window, and the application wasn't expecting you to, so Windows terminated it for you.
Sorry, but I don't know how to catch a console window close event in managed code.

Related

Console.WriteLine stops execution on Windows 10 until I press enter

I found no solution/answer to this.
private void LogToConsole(EventLog eventLog)
{
var type = TypeToStringOfUniFormLength(eventLog.Type);
Console.WriteLine($"# {type} {eventLog.Message}");
}
This i my "Event-Logger" and i have a very special behaviour. Most of time it's works great. My Console (in console-application) is updated, but sometimes it just stops at the line "Console.Writeline...". The Console is not updated and the execution pauses there. When i click in the console and hit Enter. The Console is updated an the execution continues. There is no specific scenario to reproduce. Is anybody familiar with this error, or even has a solution to this. My next work arround is to just not use a console-app for this.
thank you for your help in advance.
Windows 10 console automatically enters the Mark/Selection mode when you click it(no need to right-click->Mark, like it is with earlier windows consoles).
This is what prevents the application from printing anything, but the application actually continues to work:
The application itself keeps running, but nothing is written to the
screen.
Then
When you exit the selection mode, the process will resume as normal.
If it is not the case, then you will have to debug/dump your application to determine the culprit.

Most ungraceful way to terminate a process (that's being terminated)?

What is the most ungraceful way to really terminate a process?
I was trying to use Process.Kill (System.Diagnostics), but it has a drawback that renders it useless for me:
If the call to the Kill method is made while the process is currently terminating, a Win32Exception is thrown for Access Denied.
I'm in fact dealing with an application (which isn't mine) that crashes frequently and even gets stuck in the termination process in a manner that only rebooting would help.
Running TASKKILL /F /IM ... also exits with "Access denied". I also tried to P/Invoke TerminateProcess().
Although this question might be oddly specific, I'd be very thankful for an answer.
Shortly after asking this question I figured out why the application would hang in a fashion that only a reboot would help (many thanks to this answer!): Avast Anti-Virus. Once I removed that software from all workstations the 3rd party application still crashes, but it gets actually terminated after doing so and thus can be run again.
Thanks anyways!
See if this helps
private void Test(){
KillProcess("notepad");
}
private void KillProcess(string processName) {
Process[] appProcesses = Process.GetProcessesByName(processName);
if(appProcesses.Length == 0)
return;
// Kill and wait for app to exit
appProcesses[0].Kill();
appProcesses[0].WaitForExit();
}

C# is there anyway to instruct a code block to finish processing before the app gets shut down?

I know this won't work in all scenarios, but please keep in mind the following 3 scenarios:
An IIS reset - if the code is running inside IIS
A Server restart or shut down
User closes the app (if its a Windows form or Console App).
Lets say I have a code block that runs a loop. Is there a way to ensure at least that the current loop item gets processed before the app shuts down.
Like this...
Loop runs: 100 items, app gets shutdown (for reasons above), app is busy with item in loop 53 for example. It first finishes all code for that item between the foreach... and then allows the app to gracefully shutdown.
Is this type of thing possible?
Nothing I would do but If it is ok to abuse the system you might be able to use the CriticalFinalizerObject
It is guaranteed to execute
even in situations where the CLR forcibly unloads an application domain or aborts a thread
I really don't think so. You are stuck in front of windows. Windows take that kind of decisions for you.. IF somebody is shutting down the pc, then you are just shut down. This is the same scenario as if they where a power failure. What will you do in that case?
For a normal application: While your code is running in a foreground thread (not ThreadPool or Thread.IsBackground == true) it will not be aborted mid-execution, unless the user forcibly quits the process.
If you are running your loop in a background thread, you can try handling the exit event of the application, waiting for the loop to finish or at least reach a stable state before being aborted.
In most apps you can handle close event and not allow it but you can't do anything when user decides to kill your process. So i would say that its not possible.
How about doing this. using a try catch and finally in the static void Main
Here even if you end task the application, finally will run. not sure about power failure.
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
try
{
Application.Run(new Form1());
}
finally
{
MessageBox.Show("I run always.");
}
}
Hope it helps

Running a cleanup after a program crashes

I'm currently writing quite a simple app, but it makes a change to the OS which gets changed back when the program is closed.
The worry of course, is if the program crashes. I can do everything in my power to prevent it from crashing, or handling things if it does crash - but I can't stop someone from force closing the process (unless I can?)
Is there a way to catch that event and run just a very quick cleanup before the process exits?
I don't think there is anything you can do if your process gets killed - one approach would be to have your app spawn a helper process that is just there for this case. When your app terminates that process can detect that and "fix" the OS setting as desired before it shuts down itself - obviously this only would work if that other process doesn't get killed first.
You can hook UnhandledException. You can't stop the application terminating, but you can log or do some clean up. This allows you to handle the case of application crashes.
It terms of someone actually just killing the process there's nothing you can do about that.
Program defensively.
Write the original settings to a file. Delete the file when closing. When starting, check whether the file is there - if it is, your process was killed and you know what to return the settings to.
Programming 201 - the basics of transactions, applied to system settings wit hthe program runtime as transaction boundary.
If you don't mind a little interop to C or C++ code, and if you're running on Windows Vista or newer, you could make use of the Application Recovery and Restart APIs. These APIs tell Windows to intercept your process when something catastrophic happens, so that you can perhaps call a little cleanup code before Windows kills the process completely.
See http://msdn.microsoft.com/en-us/library/cc948909.aspx.

C# application terminates unexpectedly

We run a C# console application that starts multiple threads to do work. The main function looks something like this:
try
{
DoWork();
}
catch (Exception err)
{
Logging.Log("Exception " + err.ToString());
}
Logging.Log("Finished");
The DoWork() function reads new jobs from a database, and spawns threads to process one work item each. Since last week, the application has started disappearing mysteriously. It disappears from the processes list and there is no entry in the event logs. The log file shows work up to a certain point: it does not log an exception, or the "Finished" line.
Any clue(s) on how a C# application can vanish like that?
EDIT: Threads are created like:
new Thread(SomeObj.StartFunc).Start();
Some of the disappearances occur when no threads are running.
P.S. We installed DebugDiag with a rule to create a crash dump whenever our program crashed. It did not create any dump files when the process disappeared.
You need to have a similar catch block at the top level of the function that every thread works. If there is an uncaught exception on a thread it will kill the application, and the catch block on the main thread is not going to help.
What's the identity that you're using to run the console application?
Also, you might want to use SetConsoleCtrlHandler to capture the console events. Look at this blog post for more details. We had a similar issue when the console application was run under a service account, and it would occasionally get terminated. I'm not sure if this is what you're running into. Let me know I can post some code.
UPDATE: It looks like your scenario resembles what we had experienced. In your console event handler, you need to check for the LogOff event and return true. Look at this KB article.
public static void inputHandler(ConsoleCtrl.ConsoleEvent consoleEvent)
{
if (ConsoleEvent == ConsoleCtrl.ConsoleEvent.CtrlLogOff)
return true;
return false;
}
It's possible that one of the threads that the DoWork method is spawning is throwing an exception. The default behavior in this case is for the process to terminate. You can stop this from happening by using the AppDomain.UnhandledException event to override the default behavior.
A console program quits when the main function exits. Since DoWork just spawns a few threads it's returning control to main right away, and since Main has nothing else to do it exits and the program ends. At this time the threads spawned by DoWork are also killed.
That it worked before means either there was something in DoWork() to wait on those threads that now returns right away (is broken) or that part still works but a thread that used to take a long time to return now aborts and returns right away.
It could perhaps be the Logging.Log function that throws your exception.
I have managed to make programs disappear without a trace in a similar fashion to you (no exception traces and no termination log messages) in the past. Almost all the time it was related to killing the stack (the name of this website always reminds me).
It is possible that you are suddenly trying to process far more data than usual, or using re-entrant routines, or being 'clever' with pointers.
DISCLAIMER: My experience was with a Win32 C++ application, not C#.
It could be a memory leak. If your application takes too much memory, Windows will kill it. You can check how much memory you are using: if it grows over time, you may have a memory leak.
Another possibility is that somewhere, you have code calling Environment.Exit(). Try a full text search through your code to double-check. You never know!
Be careful; there are some exceptions that cannot be caught: OutOfMemoryException and StackOverflowException.
Therefore your program will die terribly, but silently.

Categories

Resources