SQL Server Can i use DateTimeOffset.UtcNow.UtcTicks as unique value in db primary column?

1qczuiv0  于 2023-05-16  发布在  其他
关注(0)|答案(2)|浏览(139)

I am using below code to generate unique id value from C# to save in db primary column. DBs like SQL, Mongodb, AWS redhsift (on these dbs i have unique id column) Can I go forward or is there complication in future ?

var milliSeconds = DateTimeOffset.UtcNow.UtcTicks.ToString();

long id = long.Parse(milliSeconds)

Thanks

r7knjye2

r7knjye21#

You can create a singleton class for it which contains a private counter and a method to retrieve the counter. However, the retrieve method has a lock so it get executed one thread at a time. Since it's a singleton class, it will instantiate once when the program gets run and you can initialize your counter from the maximum value available for id in your database and after that it would get increased without duplication or interruption.

Here's some sample code in console:

class Program
{
    static void Main(string[] args)
    {
        for (int i = 0; i < 10; i++)
        {
            var counter = SingletonCounter.GetInstance();
            ThreadStart start = new ThreadStart(delegate
            {
                var id = counter.GetId();
            });
            new Thread(start).Start();
        }

        Console.ReadLine();
    }
}

public class SingletonCounter
{
    private static SingletonCounter _instance;
    private readonly object _object = new object();
    private long _id;
    private SingletonCounter()
    {
        _id = 0;//you can initiate with maximum id available in database when run the application
    }

    public static SingletonCounter GetInstance()
    {
        return _instance ??= new SingletonCounter();
    }

    public long GetId()
    {
        lock (_object)
        {
            Console.WriteLine(_id);
            return _id++;
        }
    }
}
ubof19bj

ubof19bj2#

I am using another way to generate the unique bigint value it's works 99% but 1% is chance is that the project runs on multiple servers(load balancers)

public static int _staticNum = 1;
private static readonly object syncLock = new object();

 public static int GenerateStaticNum()
    {
        lock (syncLock)
        { // synchronize
            if (_staticNum == 99)
                _staticNum = 0;
            return _staticNum++;
        }
    }

    public long LatestScocuUniqueId()
    {
        string milliSeconds = DateTimeOffset.UtcNow.UtcTicks.ToString();
        int staticValue = GenerateStaticNum();
        string uid = milliSeconds.Substring(1);
        uid = uid + (staticValue < 10 ? "0" + staticValue.ToString() : staticValue.ToString());
        long id = long.Parse(uid);
        return id;
    }

Console.WriteLine(LatestScocuUniqueId());

相关问题