| | | 1 | | using System.Collections.Concurrent; |
| | | 2 | | |
| | | 3 | | namespace CounterpointCollective.Threading |
| | | 4 | | { |
| | | 5 | | public static class ConcurrentDictionaryExtensions |
| | | 6 | | { |
| | | 7 | | /// <summary> |
| | | 8 | | /// Atomic update. Will retry on concurrent writes. |
| | | 9 | | /// </summary> |
| | | 10 | | /// <typeparam name="TKey"></typeparam> |
| | | 11 | | /// <typeparam name="TValue"></typeparam> |
| | | 12 | | /// <param name="d">The dictionary to update.</param> |
| | | 13 | | /// <param name="k">The key to update.</param> |
| | | 14 | | /// <param name="update">May be called multiple times on concurrent writes</param> |
| | | 15 | | /// <param name="v">The initial value to check against.</param> |
| | | 16 | | /// <returns>The final value as written into <paramref name="d"/></returns> |
| | | 17 | | public static TValue Update<TKey, TValue>( |
| | | 18 | | this ConcurrentDictionary<TKey, TValue> d, |
| | | 19 | | TKey k, |
| | | 20 | | Func<TKey, TValue, TValue> update, |
| | | 21 | | TValue v |
| | | 22 | | ) |
| | | 23 | | where TKey : notnull |
| | | 24 | | { |
| | 105 | 25 | | var res = update(k, v); |
| | 105 | 26 | | while (!d.TryUpdate( |
| | 105 | 27 | | k, |
| | 105 | 28 | | res, |
| | 105 | 29 | | v |
| | 105 | 30 | | )) |
| | | 31 | | { |
| | 0 | 32 | | v = d[k]; |
| | 0 | 33 | | res = update(k, v); |
| | | 34 | | } |
| | 105 | 35 | | return res; |
| | | 36 | | } |
| | | 37 | | } |
| | | 38 | | } |