My quest is about a Unity game engine but is likely applicable to all games or all applications in general.
I'm writing a plugin for Unity which needs to yield return UnityWebRequest.SendWebRequest()
at some points in the game session. Ideally, I also need to send such request if the user closes the game (e.g. by closing the window from the operating system where the game runs).
Unity's onApplicationQuit
pre-defined callback would do, however it seems that I can't start a coroutine (an asynchronous operation) there because at application termination all gameObjects are getting destroyed and there is simply not enough time to process the web request: not in one frame, not even in a few frames if there were any "grace period" at application closure.
How do games solve such issues? How do applications in general solve it? It's about launching an asynch operation at a point when everything is getting destroyed and the operating system won't wait around for your application to receive the result or even to send the request in the first place.
A solution that comes to mind is to try to send data regularly. However, I'm already doing that. So, the problem is with that last request which doesn't get sent because the application is getting closed abruptly.
Another solution I could think of is to store data which needs to be send (e.g. to PlayerPrefs or to simply to some custom file in my own format) and on the next app launch check if there is any data pending to be sent. However, this won't always work for my case because:
Yet another solution: download an executalbe file and when the game is closed then in onApplicationQuit use System.Diagnostics.Process
to run that executable and do the request in the background. So, basically, after the game window is closed, I'd have another process doing the clean up and reporting. However, this is bad in 2 respects:
Any other solutions?
(Btw I've already given up on the cases when the application crashes - I don't expect to be able to send anything at that point except the requests I was already sending regularly)
Another possible solution to look into is https://docs.unity3d.com/ScriptReference/Application-wantsToQuit.html.
Unity raises this event when the player application wants to quit.
Add an event handler to this event to receive a notification that application is attempting to quit.
When this event is raised the quit process has started but can be cancelled. This means the player is not guaranteed to quit. For a guaranteed quit event take a look at Application.quitting.
Return true and the quit process will continue. Return false and the quit process will cancel.
You would catch the user wanting to quit, send your web request and when it's done, call Application.Quit
yourself.