/// <summary> /// Closes every possible connections from this object to the server. /// This method also set appropriate flags for stored game data on server, /// as well as (might be) triggering GC with null values /// </summary> public void Close(bool deleteData = false) { if (!IsConnectionClosed) { string role = _role.ToString(); bool isHost = _role == MultiplayerRole.Host; // sudden close if (CurrentData?.State == GameState.Playing) { CurrentData?.ChangeGameState( isHost ? GameState.HostExited : GameState.GuestExited, true, true ); } // stop the stop watch _stopWatch.Stop(); // cancel the token source first _tokenSource.Cancel(); _mainTask.Wait(); _mainTask.Dispose(); Logger.Log($"Main task finished from {role}"); // then free up every tasks _uploadTask.Close(); _downloadTask.Close(); Logger.Log($"Other tasks also finished from {role}"); // set to null for next check / gc invoker _tokenSource = null; _mainTask = null; _uploadTask = null; _downloadTask = null; // leave only settings and game state behind, not deleting all of it... if (deleteData) { // delete parts of the game Firebase.Delete(GetLink("host")).Wait(Constants.TIMEOUT); Firebase.Delete(GetLink("opponent")).Wait(Constants.TIMEOUT); } // set flag IsConnectionClosed = true; // log Logger.Log($"Successfully closed connection to the server from {role}"); } }