Is there an event triggered before editor starts rebuilding scripts?

I have threads and sockets that need to be handled before closing the application. This is being done in OnApplicationQuit . If I do not handle these then the editor hangs and must be force quit in task manager (Windows 10, Unity 5.4.1).

If I am unlucky or stupid or both and leave the application playing in the editor and save an edited script in Visual Studio then a rebuild is triggered in the editor. Is there an editor event or something that I could use to detect this and gracefully dispose my threads and sockets?

I am using NetMQ and the issue with Unity hanging is further described here: Unity get stuck #526

@Mikael-H Are you doing this in a MonoBehaviour or ScriptableObject? If so, be advised that on a domain reload (e.g., if you trigger scripts to recompile), your MonoBehaviour will invoke OnDisable()/OnEnable() as everything is deserialized/serialized. You should probably dispose your threads in OnDisable() rather than OnApplicationQuit() and it should catch both cases.

(Be aware of course OnDisable() will also be called if MonoBehaviour.enabled is set to false.)