forked from sergiisyrovatchenko/SQLIndexManager
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConnectionList.cs
More file actions
78 lines (63 loc) · 1.84 KB
/
Copy pathConnectionList.cs
File metadata and controls
78 lines (63 loc) · 1.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Threading;
namespace SQLIndexManager {
public class ConnectionList : IDisposable {
bool _disposed;
readonly IDictionary<string, SqlConnection> _databases = new Dictionary<string, SqlConnection>();
public ConnectionList(Host host) {
foreach(string database in host.Databases) {
SqlConnection connection = Connection.Create(host, database);
_databases.Add(database, connection);
}
}
public SqlConnection Get(string database) {
if (!_databases.ContainsKey(database))
return null;
SqlConnection connection = _databases[database];
if (!connection.State.HasFlag(ConnectionState.Open)) {
short retries = 0;
while (true) {
try {
connection.Open();
break;
}
catch (SqlException ex) {
retries++;
Output.Current.Add($"Open connection: {database}", ex.Message);
if (retries > 2 || ex.Number == 4060) {
_databases.Remove(database);
return null;
}
if (ex.Number == 40615 || ex.Number == 18456) {
Thread.Sleep(2000);
}
}
}
}
return connection;
}
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing) {
if (_disposed)
return;
if (disposing) {
foreach (var item in _databases) {
SqlConnection connection = item.Value;
if (connection != null && connection.State.HasFlag(ConnectionState.Open)) {
connection.Close();
}
}
}
_disposed = true;
}
~ConnectionList() {
Dispose(false);
}
}
}