构建一个线程安全的GUID增量' er

时间:2016-11-30 09:50:24

标签: c# .net multithreading guid

在我的下面的代码中,我锁定guid,尝试使其线程安全。 使用我的示例应用程序,我将获得一个"重复键"大约每10次我运行该程序。阿卡,我得到了一份副本,这不是我需要的。

无论如何都要制作" .NextGuid"线程安全?

using System;    
namespace MyConsoleOne.BAL
{
    public class GuidStore
    {
        private static object objectlock = new object();    
        private Guid StartingGuid { get; set; }    
        private Guid? LastGuidHolder { get; set; }    
        public GuidStore(Guid startingGuid)
        {
            this.StartingGuid = startingGuid;
        }

        public Guid? GetNextGuid()
        {
            lock (objectlock)
            {
                if (this.LastGuidHolder.HasValue)
                {
                    this.LastGuidHolder = Increment(this.LastGuidHolder.Value);
                }
                else
                {
                    this.LastGuidHolder = Increment(this.StartingGuid);
                }
            }    
            return this.LastGuidHolder;
        }

        private Guid Increment(Guid guid)
        {    
            byte[] bytes = guid.ToByteArray();    
            byte[] order = { 15, 14, 13, 12, 11, 10, 9, 8, 6, 7, 4, 5, 0, 1, 2, 3 };    
            for (int i = 0; i < 16; i++)
            {
                if (bytes[order[i]] == byte.MaxValue)
                {
                    bytes[order[i]] = 0;
                }
                else
                {
                    bytes[order[i]]++;
                    return new Guid(bytes);
                }
            }    
            throw new OverflowException("Guid.Increment failed.");
        }
    }
}

using MyConsoleOne.BAL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyConsoleOne
{
    class Program
    {
        static void Main(string[] args)
        {
            GuidStore gs = new GuidStore(Guid.NewGuid());

            for (int i = 0; i < 1000; i++)
            {
                Console.WriteLine(i);
                Dictionary<Guid, int> guids = new Dictionary<Guid, int>();
                Parallel.For(0, 1000, j =>
                {
                    Guid? currentGuid = gs.GetNextGuid();
                    guids.Add(currentGuid.Value, j);
                    Console.WriteLine(currentGuid);
                }); // Parallel.For
            }    
            Console.WriteLine("Press ENTER to Exit");
            Console.ReadLine();
        }
    }
}

我的代码是:

的组合

因为我得到&#34;为什么不使用Guid.NewGuid&#34;问题,我在这里提供原因:

我有一个父进程,它有一个由Guid.NewGuid()创建的uniqueidentifier。我将此称为&#34;父母guid&#34;。该父进程将创建N个文件。如果我是从头开始写作,我只会附加&#34; N&#34;在文件名的末尾。因此,如果父母Guid是&#34; 11111111-1111-1111-1111-111111111111&#34;例如,我会写文件

"11111111-1111-1111-1111-111111111111_1.txt"
"11111111-1111-1111-1111-111111111111_2.txt"
"11111111-1111-1111-1111-111111111111_3.txt"

等,但是,通过现有的&#34;合同&#34;与客户端:::文件名必须有一个(唯一的)Guid,而不是#34; N&#34; (1,2,等等)文件名中的值(这个&#34;合同&#34;已存在多年,所以它几乎是一成不变的)。通过这里列出的功能,我可以保留&#34;合同&#34;,但文件名与&#34; parent&#34;松散地联系在一起。 Guid(父母再次由Guid.NewGuid()生成)。碰撞 NOT 是文件名的问题(它们被放在一个不同的文件夹下,用于&#39;进程&#39;执行)。碰撞是&#34;父母的问题&#34; GUID。但同样,这已经用Guid.NewGuid处理了。

因此,使用&#34; 11111111-1111-1111-1111-111111111111&#34;的起始Guid,我将能够编写如下文件名:

OTHERSTUFF_111111111-1111-1111-1111-111111111112_MORESTUFF.txt
OTHERSTUFF_111111111-1111-1111-1111-111111111113_MORESTUFF.txt
OTHERSTUFF_111111111-1111-1111-1111-111111111114_MORESTUFF.txt
OTHERSTUFF_111111111-1111-1111-1111-111111111115_MORESTUFF.txt
OTHERSTUFF_111111111-1111-1111-1111-111111111116_MORESTUFF.txt
OTHERSTUFF_111111111-1111-1111-1111-111111111117_MORESTUFF.txt
OTHERSTUFF_111111111-1111-1111-1111-111111111118_MORESTUFF.txt
OTHERSTUFF_111111111-1111-1111-1111-111111111119_MORESTUFF.txt
OTHERSTUFF_111111111-1111-1111-1111-11111111111a_MORESTUFF.txt
OTHERSTUFF_111111111-1111-1111-1111-11111111111b_MORESTUFF.txt

所以在我上面的例子中,&#34;父母guid&#34;用#34; this.StartingGuid&#34; ....然后我得到&#34;递增&#34;指导原则。

还有。我可以编写更好的单元测试,因为现在我会提前知道文件名。

APPEND:

最终版代码:

public class GuidStore
{
    private static object objectlock = new object();

    private static int[] byteOrder = { 15, 14, 13, 12, 11, 10, 9, 8, 6, 7, 4, 5, 0, 1, 2, 3 };

    private Guid StartingGuid { get; set; }

    private Guid? LastGuidHolder { get; set; }

    public GuidStore(Guid startingGuid)
    {
        this.StartingGuid = startingGuid;
    }

    public Guid GetNextGuid()
    {
        return this.GetNextGuid(0);
    }

    public Guid GetNextGuid(int firstGuidOffSet)
    {
        lock (objectlock)
        {
            if (this.LastGuidHolder.HasValue)
            {
                this.LastGuidHolder = Increment(this.LastGuidHolder.Value);
            }
            else
            {
                this.LastGuidHolder = Increment(this.StartingGuid);
                for (int i = 0; i < firstGuidOffSet; i++)
                {
                    this.LastGuidHolder = Increment(this.LastGuidHolder.Value);
                }
            }

            return this.LastGuidHolder.Value;
        }
    }

    private static Guid Increment(Guid guid)
    {
        var bytes = guid.ToByteArray();
        var canIncrement = byteOrder.Any(i => ++bytes[i] != 0);
        return new Guid(canIncrement ? bytes : new byte[16]);
    }
}

和UnitTests:

public class GuidStoreUnitTests
{
    [TestMethod]
    public void GetNextGuidSimpleTest()
    {
        Guid startingGuid = new Guid("11111111-1111-1111-1111-111111111111");
        GuidStore gs = new GuidStore(startingGuid);


        List<Guid> guids = new List<Guid>();

        const int GuidCount = 10;

        for (int i = 0; i < GuidCount; i++)
        {
            guids.Add(gs.GetNextGuid());
        }

        Assert.IsNotNull(guids);
        Assert.AreEqual(GuidCount, guids.Count);
        Assert.IsNotNull(guids.FirstOrDefault(g => g == new Guid("11111111-1111-1111-1111-111111111112")));
        Assert.IsNotNull(guids.FirstOrDefault(g => g == new Guid("11111111-1111-1111-1111-111111111113")));
        Assert.IsNotNull(guids.FirstOrDefault(g => g == new Guid("11111111-1111-1111-1111-111111111114")));
        Assert.IsNotNull(guids.FirstOrDefault(g => g == new Guid("11111111-1111-1111-1111-111111111115")));
        Assert.IsNotNull(guids.FirstOrDefault(g => g == new Guid("11111111-1111-1111-1111-111111111116")));
        Assert.IsNotNull(guids.FirstOrDefault(g => g == new Guid("11111111-1111-1111-1111-111111111117")));
        Assert.IsNotNull(guids.FirstOrDefault(g => g == new Guid("11111111-1111-1111-1111-111111111118")));
        Assert.IsNotNull(guids.FirstOrDefault(g => g == new Guid("11111111-1111-1111-1111-111111111119")));
        Assert.IsNotNull(guids.FirstOrDefault(g => g == new Guid("11111111-1111-1111-1111-11111111111a")));
        Assert.IsNotNull(guids.FirstOrDefault(g => g == new Guid("11111111-1111-1111-1111-11111111111b")));
    }

    [TestMethod]
    public void GetNextGuidWithOffsetSimpleTest()
    {
        Guid startingGuid = new Guid("11111111-1111-1111-1111-111111111111");
        GuidStore gs = new GuidStore(startingGuid);

        List<Guid> guids = new List<Guid>();

        const int OffSet = 10;

        guids.Add(gs.GetNextGuid(OffSet));

        Assert.IsNotNull(guids);
        Assert.AreEqual(1, guids.Count);

        Assert.IsNotNull(guids.FirstOrDefault(g => g == new Guid("11111111-1111-1111-1111-11111111111c")));
    }

    [TestMethod]
    public void GetNextGuidMaxRolloverTest()
    {
        Guid startingGuid = new Guid("ffffffff-ffff-ffff-ffff-ffffffffffff");
        GuidStore gs = new GuidStore(startingGuid);

        List<Guid> guids = new List<Guid>();

        const int OffSet = 10;

        guids.Add(gs.GetNextGuid(OffSet));

        Assert.IsNotNull(guids);
        Assert.AreEqual(1, guids.Count);

        Assert.IsNotNull(guids.FirstOrDefault(g => g == Guid.Empty));
    }

    [TestMethod]
    public void GetNextGuidThreadSafeTest()
    {
        Guid startingGuid = Guid.NewGuid();
        GuidStore gs = new GuidStore(startingGuid);

        /* The "key" of the ConcurrentDictionary must be unique, so this will catch any duplicates */
        ConcurrentDictionary<Guid, int> guids = new ConcurrentDictionary<Guid, int>();
        Parallel.For(
            0,
            1000,
            j =>
            {
                Guid currentGuid = gs.GetNextGuid();
                if (!guids.TryAdd(currentGuid, j))
                {
                    throw new ArgumentOutOfRangeException("GuidStore.GetNextGuid ThreadSafe Test Failed");
                }
            }); // Parallel.For
    }

    [TestMethod]
    public void GetNextGuidTwoRunsProduceSameResultsTest()
    {
        Guid startingGuid = Guid.NewGuid();

        GuidStore gsOne = new GuidStore(startingGuid);

        /* The "key" of the ConcurrentDictionary must be unique, so this will catch any duplicates */
        ConcurrentDictionary<Guid, int> setOneGuids = new ConcurrentDictionary<Guid, int>();
        Parallel.For(
            0,
            1000,
            j =>
            {
                Guid currentGuid = gsOne.GetNextGuid();
                if (!setOneGuids.TryAdd(currentGuid, j))
                {
                    throw new ArgumentOutOfRangeException("GuidStore.GetNextGuid ThreadSafe Test Failed");
                }
            }); // Parallel.For

        gsOne = null;

        GuidStore gsTwo = new GuidStore(startingGuid);

        /* The "key" of the ConcurrentDictionary must be unique, so this will catch any duplicates */
        ConcurrentDictionary<Guid, int> setTwoGuids = new ConcurrentDictionary<Guid, int>();
        Parallel.For(
                0,
                1000,
                j =>
                {
                    Guid currentGuid = gsTwo.GetNextGuid();
                    if (!setTwoGuids.TryAdd(currentGuid, j))
                    {
                        throw new ArgumentOutOfRangeException("GuidStore.GetNextGuid ThreadSafe Test Failed");
                    }
                }); // Parallel.For

        bool equal = setOneGuids.Select(g => g.Key).OrderBy(i => i).SequenceEqual(
                         setTwoGuids.Select(g => g.Key).OrderBy(i => i), new GuidComparer<Guid>());

        Assert.IsTrue(equal);
    }
}

internal class GuidComparer<Guid> : IEqualityComparer<Guid>
{
    public bool Equals(Guid x, Guid y)
    {
        return x.Equals(y);
    }

    public int GetHashCode(Guid obj)
    {
        return 0;
    }
}

1 个答案:

答案 0 :(得分:6)

这里有两个问题:

  1. Dictionary.Add()不是线程安全的。请改用ConcurrentDictionary.TryAdd()
  2. GetNextGuid()的实现存在竞争条件,因为您正在锁定之外返回this.LastGuidHolder,因此可以在返回之前由另一个线程进行修改。
  3. 一个明显的解决方案是在锁内移动返回:

    public Guid? GetNextGuid()
    {
        lock (objectlock)
        {
            if (this.LastGuidHolder.HasValue)
            {
                this.LastGuidHolder = Increment(this.LastGuidHolder.Value);
            }
            else
            {
                this.LastGuidHolder = Increment(this.StartingGuid);
            }
    
            return this.LastGuidHolder;
        }
    }
    

    但是,我会将返回类型更改为Guid - 它似乎没有任何目的可以返回Guid? - 这应该隐藏在里面的东西班级:

    public Guid GetNextGuid()
    {
        lock (objectlock)
        {
            if (this.LastGuidHolder.HasValue)
            {
                this.LastGuidHolder = Increment(this.LastGuidHolder.Value);
            }
            else
            {
                this.LastGuidHolder = Increment(this.StartingGuid);
            }
    
            return this.LastGuidHolder.Value;
        }
    }
    

    以下是使用ConcurrentDictionary的测试方法的一个版本:

    static void Main(string[] args)
    {
        GuidStore gs = new GuidStore(Guid.NewGuid());
    
        for (int i = 0; i < 1000; i++)
        {
            Console.WriteLine(i);
            ConcurrentDictionary<Guid, int> guids = new ConcurrentDictionary<Guid, int>();
            Parallel.For(0, 1000, j =>
            {
                Guid currentGuid = gs.GetNextGuid();
                if (!guids.TryAdd(currentGuid, j))
                {
                    Console.WriteLine("Duplicate found!");
                }
            }); // Parallel.For
        }
    
        Console.WriteLine("Press ENTER to Exit");
        Console.ReadLine();
    }
    

    说了这么多,我无法理解你为什么不只是使用Guid.NewGuid() ...