NativeWebSocket icon indicating copy to clipboard operation
NativeWebSocket copied to clipboard

Game freezes when focusing back

Open ftzi opened this issue 2 years ago • 4 comments

I am using the snippet given in the README. On OnMessage, I do some complex and quite big data changes. I have ~20 messages per second.

The game works fine when it's focused, but when I alt-tab it, leave it there for some time, and go back, it gets frozen for a significant time. It seems that all the messages are queued while it's unfocused (as Update() doesn't seem to be happening) and then are processed when it gets focused again.

Anyway to fix this issue? It would be good if I could process the messages / call websocket.DispatchMessageQueue() outside the Update().

ftzi avatar May 29 '23 13:05 ftzi

It seems that

void Awake() {
    Application.runInBackground = true;
}

helps. But, I believe it would still allow this situation under some specific circumstances. Maybe there should be a way to limit the queue / choose what to do when the queue is full?

ftzi avatar May 29 '23 13:05 ftzi

Hi @SrBrahma, thanks for the feedback. The raw receive loop can be found here: https://github.com/endel/NativeWebSocket/blob/4cecff9c914b764549d32c2efdd8dd5f3cb0d911/NativeWebSocket/Assets/WebSocket/WebSocket.cs#L641-L702

I'm not sure await new WaitForBackgroundThread() would block while the app is not focused. I believe different strategies could suit different needs in such scenario. On Colyseus, for example, every message must arrive in order to have the state synchronized properly.

Perhaps a global/static option for max queued messages could be nice. A PR would be welcome for this! Cheers!

endel avatar May 30 '23 18:05 endel

Sorry, I am still a beginner in C#/Unity (started less than a month ago) and i am not able to understand this or to provide a PR 😅

ftzi avatar May 30 '23 20:05 ftzi

But, the thing is that Update(), that calls that dispatch, is only called when the app is focused. That's what GPT at least told me about the Update(), and that Application.runInBackground solution worked.

ftzi avatar May 30 '23 20:05 ftzi