C# Debugging: magical System Clock restore - c#

The program I am working on is used to test operations in a time-based schedule. As such, one of the requirements is to change the system clock to provoke another application into firing events. This is simple enough. My program runs a script, which can set the clock. When the script starts, I store the DateTime.Now and create a Stopwatch. When the script ends, if it has modified the system clock I read the elapsed time, add it to my start time, and set the system clock that value. All fine so far. HOWEVER. If I debug my program and stop it before the script ends, that restore never happens. I was wondering if there was any way to get the C# debugger to forcibly call some piece of code (or perform some action such as reading the time from an NIST server) when it shuts down?

Stopping the debugger is the same as terminating the process, so there is no guarantee, what is happening.
Nevertheless consider to implement a dispose or a finalize method.

"I debug my program and stop it..."
So you're wondering why your program doesn't continue after you've stopped it?
You can debug your program and then simply detach the debugger when you're done - this will leave the program running.

Related

C# Exclude Threads from Debugger to prevent them being suspended

I've got the following code:
https://github.com/YatoDev/Yato.LowLevelInput/blob/master/Yato.LowLevelInput/WindowsHooks/WindowsHook.cs
I am using this for LowLevelMouse and LowLevelKeyboard hooks.
When i debug the application and pause it, the hook wont execute.
This results in input lags for at least 10 seconds
I also tested it using CreateThread instead of a managed thread (also with the HideFromDebugger flag)
Sadly, it does not help.
It seems like the c# debugger freezes any thread that executes managed code.
I wonder if there is a way to exclude my hook threads to prevent them being suspended.
Note: I searched for this problem but i did not find an answer providing an automated solution. I hope to find a way to exclude them by Thread.Name.Contains("Foo") or by setting up the debugger to never suspend all threads.

Executing a program before System Shutdown

I have a program I need to run before a system shutdown executes. This means, before any program gets terminated because of the shutdown, I need to execute said program, ideally via Process.Start().
Initially I tried executing said program in the Windows Shutdown Scripts, however that script is only executed after programs have already been terminated. I however need to terminate some running applications in the right order.
I have tried the event SystemEvents.SessionEnding and SessionEnded, but this event does not let you wait for more than 1-2 seconds, and the cancelling of the shutdown is not possible either.
I got up to this example where, in the WndProc event about shutdown I would execute a Process. I reach the Event, I reach the point where I can actually pause the shutdown process. However, when I try to actually call a process, I get the "0xC0000142" error.
A search for this resulted in one option being that the user is incorrect, however I want to call this application with the user that is running the executing program. The other option was that the environment path was wrong. I set an environment path for the second option, but in my opinion, I shouldn't need to change anything for the first option, since I want to execute it with the current user.
A third possibility I thought about might be that at this state of the system shutdown, no new processes can be spawned.
What can I do to fix this and actually execute the program here? I seem to be out of ideas at this point.
Clarification:
The "cleanup" program needs to shut down programs in a given order. The programs to be shut down are our own, but Windows Forms (the only way I can see that can use a shutdown handler) cannot be used there.
Program A is the one that handles the OnShutdown. Program A, on Shutdown, will call Program B, which does the ordered closing of programs. Program B, in my solution (that includes Forms) cannot be launched and returns an error, as specified in paragraph 4. The only user interaction here would be a user pressing a power button leading to system shutdown, or a remotely executed "shutdown.exe" call.

Appccelerate state machine state with timer

Ok I am sure I am not using the state machine correctly but here is subset of sample code. This is the Appccelerate.StateMachine which used to be bbvcommon.StateMachine.
fsm.In(State.Idle)
.ExecuteOnEntry(() => {
// wake up and check if there are people still standing and if so restart
if(currentlyTalkingTo.Count() > 0)
{
fsm.Fire(Event.PersonFound);
}
})
.On(Event.PersonFound).Goto(State.WaitToRecognizePeople);
fsm.In(State.WaitToRecognizePeople)
.ExecuteOnEntry(() => {
Thread.Sleep(1000);
fsm.Fire(Event.TimeOut);
})
.On(Event.TimeOut).Goto(State.Greet);
The issue is what the best way to handle a sleep? With this code calling fsm.Stop() when shutting the application down sometimes hangs the application. Commenting all the Thread.Sleeps() in the states fixes the issue so the application successfully shuts down.
What is the recommended way of handling states that need to time out and move to another state? Sample code would be appreciated.
The Thread.Sleep would block the state machine, both the PassiveStateMachine and ActiveStateMachine, so that you cannot react to other events anymore during the sleep time. That might be an explanation for why a call to Stop sometimes hangs the explanation.
I assume you don't just want to wait for a given period of time but want to wait for some event under a timeout condition. I would then recommend to start a Timer in the ExecuteOnEntry of WaitToRecognizePeople that, when elapsed, fires the event Event.Timeout.
If you have many states that have associated timeouts, to avoid a lot of duplicated code, you could even implement this in a separate class as a state machine extension, like I did in one of my projects using this library. (see http://www.appccelerate.com/statemachineextensions.html).

write a program which runs in background and perform actions every hour

I would like to write an application in C# which runs in the background most of the time. It should only show a TrayIcon. For this I found a tutorial: http://www.simple-talk.com/dotnet/.net-framework/creating-tray-applications-in-.net-a-practical-guide/
But how can I tell my program to run every hour? Whats the best way to implement this. A timer? The app should use as less as possible resources while doing nothing.
thanks
Don't have a program that runs all the time but only performs activity every hour. Write a program that performs the activity and then schedule it hourly using Task Scheduler in windows.
Question: is the program you're doing a "user space" program, or should it run even if a user is not logged in? In other words, should it always be on?
Basically, are you doing something useful to a user, or is this for a business task like archiving a web server's log files to database?
If it's the former, keep doing your notification area program. If it's the latter, skip the notification area program and build a full-out Windows Service.
In both cases, use a timer; resource use will be minimal.
Not sure of the processing cost, but you could code in a sleep timer to put it to sleep for an hour in a loop so it will wake up, run, then sleep again. Not sure of the drain on resources when sleeping though. Also, if the program might take a few minutes, you could calculate sleep time based on the DateTime.Now DateTime object so it wakes up every hour on the hour.

Knowing At what point the application freezes

I am developing a WinForm multithreaded application with C#.
Sometimes it happens that my application hangs, or freezes or blocks.
When this happens and I am running in DEBUG mode, is there anyway to understand at what line of code my application is currently? Since it is freezed I expect to find a point where the application is locked or blocked or whatever.
Is it possible to do that someway?
When It is freezed I tried to open the CALL STACK window, but this doesn't display any info; is there some action that I might do? Some "pause and check" or whatever?
You may need to open the Threads window, and change the current thread. While debugging, choose Debug->Break All, and open the Threads window. If you go through each thread, by double clicking on the thread, you should be able to investigate the call stack for each thread.
That being said, if you can run your program in VS 2010 - this gets a lot easier. In VS 2010, you can use the new Concurrency Profiler, and run your code under the Concurrency Profiler with the option to Visualize the Behavior of a multithreaded application. Once your application locks up, kill it, and let the profiler churn -
Eventually, you'll get a diagram which shows each thread in your program, and when they're locked. The callstack for each blocked thread will be shown, as well as what lock is being held (with the line of source code). This makes it very easy to track down a dead lock.
When debugger is attached go to Debug menu and choose 'Break All'... Then you can examine call stacks for all thread.
You could press pause and see where it ends up (use the aforementioned call stack window). Chances are however that you'll end up in native code. You could try to step out a bit or just look at the stack for a managed function to debug.
Alternatively you could put a breakpoint after the application "freezes" and try to pinpoint a loop that doesn't end.
Both the above are assuming your application is busy (100% cpu usage). If your application is however stuck in a dead lock or just plain waiting for a mutex that won't tick, you'll have to manually re-read your code and try to figure it out on your own.

Categories