~ruther/NosSmooth

ref: d4651ecd6ea052596f129f6a9783e8aeae4207f6 NosSmooth/Packets/NosSmooth.PacketSerializer/Extensions/ConcurrentDictionaryExtensions.cs -rw-r--r-- 1.5 KiB
d4651ecd — František Boháček fix: try to copy until enough size 2 years ago
                                                                                
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
//
//  ConcurrentDictionaryExtensions.cs
//
//  Copyright (c) František Boháček. All rights reserved.
//  Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Collections.Concurrent;
using Remora.Results;

namespace NosSmooth.PacketSerializer.Extensions;

/// <summary>
/// Extension methods for <see cref="ConcurrentDictionary{TKey,TValue}"/>.
/// </summary>
public static class ConcurrentDictionaryExtensions
{
    /// <summary>
    /// Adds the value from the factory if it doesn't exist already,
    /// otherwise returns the existing avlue.
    /// </summary>
    /// <param name="dictionary">The dictionary.</param>
    /// <param name="key">The key to add the value at.</param>
    /// <param name="valueFactory">The factory to obtain the value to add.</param>
    /// <typeparam name="TKey">The type of the key.</typeparam>
    /// <typeparam name="TValue">The type of the value.</typeparam>
    /// <returns>The added value.</returns>
    public static Result<TValue> GetOrAddResult<TKey, TValue>
    (
        this ConcurrentDictionary<TKey, TValue> dictionary,
        TKey key,
        Func<TKey, Result<TValue>> valueFactory
    )
        where TKey : notnull
    {
        if (dictionary.TryGetValue(key, out var val))
        {
            return val;
        }

        var result = valueFactory(key);
        if (!result.IsSuccess)
        {
            return result;
        }

        dictionary.TryAdd(key, result.Entity);
        return result;
    }
}
Do not follow this link