Datei: NDOInterfaces/ConnectionIdProvider.cs
Last Commit (e34b4f0)
| 1 | -- File didn't exist -- |
New Commit (14cacf2)
| 1 | using System; |
| 2 | using System.Collections.Concurrent; |
| 3 | using System.Collections.Generic; |
| 4 | using System.Data; |
| 5 | using System.Text; |
| 6 | using System.Threading; |
| 7 | |
| 8 | namespace NDOInterfaces |
| 9 | { |
| 10 | ····public class ConnectionIdProvider |
| 11 | ····{ |
| 12 | ········static ConcurrentDictionary<IDbConnection, int> connectionIds = new ConcurrentDictionary<IDbConnection, int>(); |
| 13 | ········static int connectionId; |
| 14 | |
| 15 | ········/// <summary> |
| 16 | ········/// This method can be used as EventHandler for the StateChange event. |
| 17 | ········/// </summary> |
| 18 | ········/// <param name="sender"></param> |
| 19 | ········/// <param name="e"></param> |
| 20 | ········public static void HandleStateChange( object sender, StateChangeEventArgs e ) |
| 21 | ········{ |
| 22 | ············if (e.CurrentState == ConnectionState.Open) |
| 23 | ················Register( (IDbConnection) sender ); |
| 24 | ············if (e.CurrentState == ConnectionState.Closed) |
| 25 | ················Unregister( (IDbConnection) sender ); |
| 26 | ········} |
| 27 | |
| 28 | ········/// <summary> |
| 29 | ········/// This should be called, if the StateChange of the connection changes to "Open". |
| 30 | ········/// </summary> |
| 31 | ········/// <param name="connection"></param> |
| 32 | ········static void Register(IDbConnection connection) |
| 33 | ········{ |
| 34 | ············// Create a new id |
| 35 | ············var nextVal = Interlocked.Increment( ref connectionId ); |
| 36 | ············// set the id for the connection |
| 37 | ············var x = connectionIds.GetOrAdd( connection, dbconn => nextVal ); |
| 38 | ········} |
| 39 | |
| 40 | ········/// <summary> |
| 41 | ········/// This should be called, if the StateChange of the connection changes from "Open" to "Closed" |
| 42 | ········/// </summary> |
| 43 | ········/// <param name="connection"></param> |
| 44 | ········static void Unregister(IDbConnection connection) |
| 45 | ········{ |
| 46 | ············connectionIds.TryRemove( connection, out _ ); |
| 47 | ········} |
| 48 | |
| 49 | ········/// <summary> |
| 50 | ········/// If a connection has been closed, it will be unregistered and it's Id is null. |
| 51 | ········/// </summary> |
| 52 | ········/// <param name="connection"></param> |
| 53 | ········/// <returns></returns> |
| 54 | ········public static int Get(IDbConnection connection) |
| 55 | ········{ |
| 56 | ············if (connectionIds.ContainsKey( connection )) |
| 57 | ················return connectionIds[connection]; |
| 58 | |
| 59 | ············return 0; |
| 60 | ········} |
| 61 | ····} |
| 62 | } |
| 63 |