Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public async Task<bool> TryOpenConnectionAsync(MySqlConnection connection, int timeoutSeconds = 20, bool hasLock = false)
- {
- if (!hasLock) await _syncLock.WaitAsync();
- try
- {
- if (connection.State == ConnectionState.Open)
- {
- // Sometimes the database gets disconnected so the program thinks the connection is active and throws an exception when trying to use it. By pinging, I make sure it's actually still connected.
- if (!await connection.PingAsync())
- {
- await connection.CloseAsync();
- return false;
- }
- else return true;
- }
- if (connection.State != ConnectionState.Closed || connection.State == ConnectionState.Connecting)
- {
- // Can't open if it's Connecting, Executing, etc.
- return false;
- }
- try
- {
- var openTask = Task.Run(async () =>
- {
- try
- {
- await connection.OpenAsync();
- return true;
- }
- catch (Exception ex)
- {
- if (ex is MySqlException mysqlEx && mysqlEx.Number == 1042)
- {
- return false;
- }
- LogError(ex);
- return false;
- }
- });
- if (await Task.WhenAny(openTask, Task.Delay(TimeSpan.FromSeconds(timeoutSeconds))) == openTask)
- {
- return openTask.Result;
- }
- else
- {
- await connection.CloseAsync(); // Clean up
- return false;
- }
- }
- catch
- {
- await connection.CloseAsync();
- return false;
- }
- }
- finally
- {
- if (!hasLock) _syncLock.Release();
- }
- }
- // Sync loop:
- Task.Run(async () =>
- {
- await Task.Delay(TimeSpan.FromSeconds(5));
- while (true)
- {
- await _syncLock.WaitAsync();
- try
- {
- await TryUploadTransactionsAsync();
- }
- catch (Exception ex)
- {
- if (ex is not MySqlException mysqlEx || mysqlEx.Number != 1042)
- LogError(ex);
- ErrorMessageBox(ex);
- }
- finally
- {
- _syncLock.Release();
- }
- await Task.Delay(TimeSpan.FromSeconds(10));
- }
- });
Advertisement
Add Comment
Please, Sign In to add comment