Improve exception handling for update checker.

This commit is contained in:
2023-07-12 23:25:15 +08:00
parent cee6a08240
commit ea70fbb051

View File

@@ -13,24 +13,40 @@ using ThreadPriority = System.Threading.ThreadPriority;
namespace Cryville.Crtr.Network { namespace Cryville.Crtr.Network {
public class UpdateChecker : MonoBehaviour { public class UpdateChecker : MonoBehaviour {
string _currentVersion; string _currentVersion;
Thread _thread;
#pragma warning disable IDE0044
bool _shutdown;
#pragma warning restore IDE0044
void Start() { void Start() {
_currentVersion = Application.version; _currentVersion = Application.version;
new Thread(CheckVersion) { IsBackground = true, Priority = ThreadPriority.BelowNormal }.Start(); _thread = new Thread(ThreadLogic) { IsBackground = true, Priority = ThreadPriority.BelowNormal };
_thread.Start();
}
void Update() {
if (!_thread.IsAlive) {
Destroy(gameObject);
if (_shutdown) Application.Quit();
}
} }
static readonly Uri BaseUri = new Uri("https://www.cryville.world/api/crtr/index"); static readonly Uri BaseUri = new Uri("https://www.cryville.world/api/crtr/index");
List<VersionInfo> _versions; List<VersionInfo> _versions;
public void CheckVersion() { void ThreadLogic() {
try { try {
var client = new Https11Client(BaseUri); CheckVersion();
client.Connect(); Logger.Log("main", 0, "Network", "Update checker exited normally");
var response = client.Request("GET", new Uri(BaseUri, "versions"));
var data = Encoding.UTF8.GetString(response.MessageBody.ReadToEnd());
_versions = JsonConvert.DeserializeObject<List<VersionInfo>>(data, Game.GlobalJsonSerializerSettings);
} }
catch (Exception ex) { catch (Exception ex) {
Logger.Log("main", 4, "Network", "An error occurred while checking for update: {0}", ex); Logger.Log("main", 4, "Network", "An error occurred while checking for update: {0}", ex);
Dialog.Show(null, "Failed to check for update."); Dialog.Show(null, "Failed to check for update.");
return; }
}
void CheckVersion() {
using (var client = new Https11Client(BaseUri)) {
client.Connect();
using (var response = client.Request("GET", new Uri(BaseUri, "versions"))) {
var data = Encoding.UTF8.GetString(response.MessageBody.ReadToEnd());
_versions = JsonConvert.DeserializeObject<List<VersionInfo>>(data, Game.GlobalJsonSerializerSettings);
}
} }
var availableVersions = _versions.Where(v => v.platforms.ContainsKey(PlatformConfig.Name)).ToArray(); var availableVersions = _versions.Where(v => v.platforms.ContainsKey(PlatformConfig.Name)).ToArray();
var versionIndex = new Dictionary<string, int>(availableVersions.Length); var versionIndex = new Dictionary<string, int>(availableVersions.Length);