Multithreading - Freeze on Second Play

Everything works fine when clicking Play the first time. After stopping once, pressing the play button again (or closing the editor) results in Unity freezing; I must close Unity via TaskManager. When reloaded it then works again, once, at which point I must repeat the process.

I assume this is being caused by threads/sockets remaining active after stopping the program in the Unity editor. Is there a way to determine which thread(s) / what is causing the problem?

For anyone coming here to find a solution.

I have written a blog post with some pointers on how to debug this issue: http://blog.tedd.no/2016/10/09/investigating-unity-hang-on-second-run-multi-threading/

There are probably multiple reasons for this to happen, but I have encountered two so far:

  1. Failure to shut down background threads.
  2. A destructor (finalizer) that hangs (deadlocked).

Connecting Visual Studio to Unity.exe through “Debug->Attach to process…” (not “Attach to Unity”), pausing it and looking at Parallel Stacks (Debug->Windows->Parallel Stacks) can give you some insights into whats going on.

Edit: Since this writing I’ve also seen a recursive function lock up Unity. 16 levelx max breadth-first search type of function. No error, Just plain old hang. Changing the function to use a queue instead of recursion fixed it.

Had the same issue. In my case a Socket connection was still open.

I had this same issue. And my problem was that the threads were still running while I pressed stop/closed the editor.

Make sure your threads are all shutdown, maybe by implementing a stop-all-threads-button that you press before pushing the stop button in the editor.

If you write any Destructors, they get called on the NEXT time you press play. Just before your new instances are constructed. It can confuse your debugging no end. I’ve had a few issues with every 2nd play crashing, and it’s always been to do with cleaning up / closing objects correctly.
This was seen on 2017.2

Using a callback to forward debug output from a plugin into the Unity log can in some cases cause a hang on second run. See this forum post for more details.

Check if you have that in your code:

Environment.Exit(0);

In my case removing that line solved the problem