Prefer fully synchronous code during saving

We must ensure no race condition during lock statement and exiting lock clause to run async code - Thread.Sleep() is bad, but we never expect to reach that point in normal conditions, and in faulty ones, it improves the chances of things succeeding in next try
This commit is contained in:
JustArchi
2016-06-27 19:05:24 +02:00
parent 5bc6af718e
commit ebc8c1674b
2 changed files with 18 additions and 18 deletions

View File

@@ -26,7 +26,7 @@ using Newtonsoft.Json;
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Threading.Tasks;
using System.Threading;
namespace ArchiSteamFarm {
internal sealed class BotDatabase {
@@ -43,7 +43,7 @@ namespace ArchiSteamFarm {
}
_LoginKey = value;
Save().Wait();
Save();
}
}
@@ -60,7 +60,7 @@ namespace ArchiSteamFarm {
}
_MobileAuthenticator = value;
Save().Wait();
Save();
}
}
@@ -78,7 +78,7 @@ namespace ArchiSteamFarm {
}
_SteamGuardAccount = value;
Save().Wait();
Save();
}
}
@@ -119,31 +119,31 @@ namespace ArchiSteamFarm {
}
FilePath = filePath;
Save().Wait();
Save();
}
// This constructor is used only by deserializer
[SuppressMessage("ReSharper", "UnusedMember.Local")]
private BotDatabase() { }
internal async Task Save() {
internal void Save() {
string json = JsonConvert.SerializeObject(this);
if (string.IsNullOrEmpty(json)) {
Logging.LogNullError(nameof(json));
return;
}
for (byte i = 0; i < 5; i++) {
lock (FilePath) {
lock (FilePath) {
for (byte i = 0; i < 5; i++) {
try {
File.WriteAllText(FilePath, json);
break;
} catch (Exception e) {
Logging.LogGenericException(e);
}
}
await Task.Delay(1000).ConfigureAwait(false);
Thread.Sleep(1000);
}
}
}
}

View File

@@ -26,7 +26,7 @@ using Newtonsoft.Json;
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Threading.Tasks;
using System.Threading;
namespace ArchiSteamFarm {
internal sealed class GlobalDatabase {
@@ -40,7 +40,7 @@ namespace ArchiSteamFarm {
}
_CellID = value;
Save().Wait();
Save();
}
}
@@ -84,31 +84,31 @@ namespace ArchiSteamFarm {
}
FilePath = filePath;
Save().Wait();
Save();
}
// This constructor is used only by deserializer
[SuppressMessage("ReSharper", "UnusedMember.Local")]
private GlobalDatabase() { }
private async Task Save() {
private void Save() {
string json = JsonConvert.SerializeObject(this);
if (string.IsNullOrEmpty(json)) {
Logging.LogNullError(nameof(json));
return;
}
for (byte i = 0; i < 5; i++) {
lock (FilePath) {
lock (FilePath) {
for (byte i = 0; i < 5; i++) {
try {
File.WriteAllText(FilePath, json);
break;
} catch (Exception e) {
Logging.LogGenericException(e);
}
}
await Task.Delay(1000).ConfigureAwait(false);
Thread.Sleep(1000);
}
}
}
}