How to save data at time an application gets killed via the Task Manager? - c++

In order to prevent application's data from losing caused by "End Task" from Task Manager, I am trying to save data at the function handler of WM_CLOSE event.
The app saves data successfully in case I closed my app via Alt+F4 or "close" button. But when I killed it via the Task Manager, the saving data process couldn't be done properly. It seems that the saving progress was terminated in middle.
I tried to debug it via VS2015 IDE, the debugger intercepted a break point in the WM_CLOSE handler successfully but it could not go further, hitting F10 to step over caused my app closes immediately.
Is there any way to delay the termination progress until my application saves data completely?
I found two links below but they didn't help.
How to handle "End Task" from Windows Task Manager on a background process?
How does task manager kill my program?

The task manager might decide that your application isn't responding, and terminate it. You can do nothing against it.
If you want to ensure that your data is always saved, you should save constantly (with some heuristics, like at least once every minute, preferrably after no change happened in a few seconds) in the background. It's more complex but has the advantage of working even when you won't receive WM_CLOSE at all, for example in the case of power loss.

Related

MFC app - Block shutdown initiated by an MSI Installer

Goal
Block or pause a reboot until my app's files have finished saving. Specifically a reboot initiated from another apps MSI installer.
Summary
The app I'm working on captures and records information during an app install on windows. Occasionally, the other app finishes installing and requires a reboot. When that happens, I need time to finish saving my files before the reboot continues.
What's Working
ShutdownBlockReasonCreate()
ShutdownBlockReasonDestory()
These work as expected; but only if I manually trigger a reboot with Start -> reboot. Windows displays the Shutdown Block message to the user with the 'force shutdown' UI (full screen blue screen)
A program is preventing shutdown.
"shutdown block reason message"
shutdown anyway?
Program Flow
my app : begin watching install process from another app
shutdown block reason create (message)
other app finishes install
You must restart your system for the configuration changes to take effect.
Click 'Yes' to restart now or 'No' if you plan to restart later.
User clicks 'Yes'
WM_QUERYENDSESSION
return false // Do not continue reboot
WM_ENDSESSION
bEnding = True
return false // App is not ready to close
ShutdownBlockReasonDestroy( ) // continue shutdown
Expected Behavior
Same behavior as when I manually start a reboot. When I return false from OnQueryEndSession() the reboot should stop, or at least pause until I have destroyed the shutdown block reason. If there is a current ShutdownBlockReason, Windows should display the shutdown block reason to the user. Windows gives the user the chance to shutdown now, wait for the process to finish, or wait and go back to save their work.
Current Behavior
The Windows Force Shutdown UI is never displayed to the user.
The BlockShutdownReason is never displayed to the user.
The app is not given time to complete the file save.
Windows asks if the shutdown can continue (WM_QUERYENDSESSION) but always follows that up with WM_ENDSESSION, bEnding = True. Windows gives minimal time to complete the file save (3 seconds) and does not give my app a chance to inform the user that a file save is in progress.
The user is not informed that a file save is in progress.
What I've Tried
Create and destroy ShutdownBlockReason
CreateProcess("C:\...\shutdown.exe /a")
AbortSystemShutdown
if I call this before the shutdown has started:
'Error: No shutdown is in progress'
if I call this after the shutdown has begun:
'Error: A shutdown is in progress'
que frustrated confused developer
Set registry key:values to not automatically shut down apps
AutoEndTasks : False
HungAppTimeout : 120_000
WaitToKillAppTimeout : 120_000
Validation
I have ensured the application has valid shutdown permissions
I have set the permissions with the app token
I have double checked that the permissions were set correctly
I have used ShutdownBlockReasonQuery() to validate that the shutdown block reason exists before during and after OnQueryEndSession and OnEndSession.
I have validated that the window is a valid top level window.
References
Windows Official Documentation
ShutdownBlockReasonCreate
ShutdownBlockReasonDestroy
Application Shutdown Changes in Windows Vista
Shutting Down
Example :: How to shut down the system
Force Reboot
Disable Automatic Application Shutdown
Enables the files in use dialog (prior to install)
Does not effect the Force Shutdown (blue screen) UI (at the end of the install)
Restart Dialog Function
ExitWindowsEx
Windows Installer : System Reboots
Blogs and Forums
Now that windows makes it harder for your problem to block shutdown, how do you block shutdown?
Stack Overflow :: Example of ShutdownBlockReasonCreate
Stack Overflow :: ShutdownBlockReasonCreate causes shutdown to be canceled after one minute
Turn off automatic termination of applications
Allows non-window applications to be considered valid when responding to "WM_QUERYENDSESSION"
My application has a top level window and should already be considered valid, as evidenced when the user clicks Start -> Reboot
SO : Is there a way to delay a forced reboot
Only applies to Windows Update reboots
Suppress a MSI Reboot
Suppress reboot from the originating installer, not a 3rd party application.
Four ways to stop a shutdown or reboot
These apply to normal reboots, not a reboot from Windows Installer, which overrides all options.
None of these solutions have provided a way to block a shutdown from the end of an install, when it asks if you want to shutdown.
They all work as expected when the user clicks Start -> shutdown, but otherwise all attempts I have made to block or delay the shutdown have failed with no message to the user, and no effect on the shutdown / reboot.

How to trigger an Apple Watch haptic feedback (or notification) from an active app after the screen just turns off?

I'm working on a standalone countdown App for Apple Watch. When the timer is over, the watch rings or vibrate.
There are three different situations where this can happen:
The app screen is active on the user's wrist: that's the easiest part; when the timer is over, the app runs a sound/haptic feedback, no need for anything running in the background. No problem with that.
The app is in the background: Using notifications seems to be the obvious choice, and it already works very well.
The app is in the foreground, but the screen turns off either because it reached the maximum wake duration (15 or 70 seconds) or because the user rotated his wrist back in rest position, which automatically turns the apple watch's screen off.
This third and last situation is where I'm confused. Neither the first nor the second situation works here: when the app is active, but the screen turns off, the app stops running, but the notifications are still not triggered since the app is technically not in the background.
Are there any straightforward ways around this problem?
Use Extended Runtime Sessions to create smart alarms
like this:
func notifyUser(hapticType type: WKHapticType,
repeatHandler: ((UnsafeMutablePointer<WKHapticType>) -> Time
Interval)? = nil)
Apple Documentation
For schedulable sessions such as smart alarms, call this method during the session to alert the user. When you call the method, the system plays repeating haptic feedback. If the app isn’t active, the system also displays a system alarm alert on the watch.
The haptic feedback repeats at the interval specified by the repeatHandler, and continues to repeat until the application or system alert invalidates the session.
If the app isn’t active, the user can tap the Stop button to invalidate the session or tap the Open button to activate the app.
If the app is active, the app must invalidate the session by calling its invalidate method.
Only call this method on a schedulable session that’s running: you must schedule the session using the startAtDate: method, and the session’s state must equal WKExtendedRuntimeSessionStateRunning. During a smart alarm session, your app must call this method before the session expires.
Also you should check out the life cycle of watchOS app

wxWidget app hangs when response from backend takes long time

I am using wxWizard, in my 3rd page I need to call a function from backend, when that function takes long time to send response, my app hangs and shows not responding in title. Once that response is recieved from backend function, app behaves normally. why this is happening? Am I doing something wrong? How should I make that app not to hang? Response from backend function is delayed because of some network issue or long processing time in backend.
See this answer. Following is an extract:
An application gets the events from a queue provided by Windows.
If the application doesn't poll the eventqueue for a while (5 seconds), for example when doing a long calculation, then Windows assumes that the application is hung and alerts the user.
To avoid that applications should push expensive calculations to worker threads or split up processing and make sure the queue gets polled regularly.
So, the problem with your code is that, In your program there is only one thread,the main thread. It is taking care of all the activity e.g. UI update, event handling, responding users etc (which are very less time consuming). But when use it comes to handle connection with backend server, it is time consuming. So, you should use another thread to handle network operations. In this way main thread will be available for its normal work and not show that it is not responding.

How to stop an ongoing upload in vc

In my application, we can upload upload files to a server. For this I am using WININET. I want to stop the upload process when user click on Stop button. Now if the user click on stop button the ongoing process will not stop uploading. How can I deny the file from uploading.
If you are using WININET, you need to post the file in several smaller chunks. If the uses presses "Cancel" you then need to set a variable to abort the upload. This must be checked after each small upload...
A full example of Splitting Uploads into smaller pparts can be found here:
http://support.microsoft.com/kb/177188/en-us
You need to download the "hsrex.exe" file and then open it with WinZip or 7-zip and extract the "BigPost.cpp" file. Also I can post the code here, if you want...
try CHttpFile::EndRequest() function...
Another idea, try to terminate the thread working for the upload operation
First, you need to be doing the WinInet stuff on a worker thread so that the UI is freed up to get the Cancel button click. When user clicks Cancel, your UI thread should close the handle being used by WinInet to upload chunks of the file. This causes WinInet to instantly abort any upload chunk currently in progress. To cleanly exit the worker thread at this point, the UI thread should set a bool 'done' flag that the worker thread reads, and if it is set, the worker thread exits instead of looping to upload another chunk.

Gracefully terminate a request based service on server

In our web application, for each http-request there is a lot of computation that happens on back end. Output can vary from 10 sec - 1 Hour. In the mean time when it is computed, "Waiting.." is shown on the website for the respective user.
But it so happens, that a user might cut down the service in between. So what all can be done on the back end so that the computation can be stopped in between to save resources? What different tactics can be applied here?
And if better (instead of killing the thread directly), then a graceful termination policy should make wonders.
I'm not sure if this fits your scenario but here is how I have tackled this issue in the past. We were generating pdf reports for a web-app. Most reports could be generated in under 5 seconds but some would take up to an hour.
When the User clicks on generate button we redirect them to a "Generating..." dialog screen which has a sort of progress bar and a Cancel button. This also launches the generate process on the server in a separate thread (we have a worker pool). The browser then polls the server regularly via ajax to check on the progress (either update the progress bar or redirect to the display page when finished).
The synchronization at the server between the generating process and the ajax process was done via a process synchronization object. The sync-obj was a very simple class instance which could be retrieved quickly from any thread at any time via some unique string.
Both processes could update this shared sync-obj. As the report generated the repgen thread would update the sync-obj which the ajax thread would inform the browser. If the User clicked the Cancel button then the ajax thread would set the "cancel" flag in the sync-ob and the repgen thread would pick that up and break out of the generate loop.
Clearly the responsiveness of the whole process depends a lot on how frequently the repgen thread checks the sync-obj and that often comes down to how the individual report was coded.
Finally, to answer your question, if the User gets bored and goes "back" and clicks the generate button again we do not cancel the first report and start a second but rather realise that it is the same report (and the same sync-obj id) and so just let the report continue. However if that does not suit your scenario then starting a generate process could cancel the first in the same manner that the User could via the Cancel button.