The last time simply said: Http://www.cnblogs.com/dunitian/p/6041745.html#uid
C # version of foreign friends have been encapsulated, we can go to see: https://github.com/ccollie/snowflake-net
powerful netizens come up with a simplified version:http://blog.csdn.net/***/article/details/*** (address I will not post, to the elders need the minimum respect)
At first I was using this simplified version and later found duplicates ... (Demo:https://github.com/dunitian/tempcode/tree/master/2016-11-16/twitter_snowflake)
Intense discussion of global IDs: https://q.cnblogs.com/q/53552/
later on the basis of the foreign Daniel rewrite the modified part of the content (Https://github.com/ccollie/snowflake-net), added some annotations and other "support core." Now it is possible to go to NuGet for direct download using:snowflake.net
Source Address: Https://github.com/dunitian/snowflake-net
Test Case:
Test code:
Using system;using system.collections.generic;using system.threading;using system.threading.tasks;using Snowflake.net;namespace snowflake.zconsole{class Program {private static int N = 2000000; private static hashset<long> set = new hashset<long> (); private static Idworker worker = new Idworker (1, 1); private static int taskcount = 0; static void Main (string[] args) {Task.run (() = GetID ()); Task.run (() = GetID ()); Task.run (() = GetID ()); Task.run (() = Printf ()); Console.readkey (); } private static void Printf () {while (Taskcount! = 3) {Console.Write Line ("..."); Thread.Sleep (1000); } Console.WriteLine (set. Count = = N * taskcount); } private static Object o = new Object (); private static void GetID () {for (var i = 0; I < N i++) {var id = worker. NextID (); Lock (o) {if (set. Contains (ID)) {Console.WriteLine ("Discovery duplicates: {0}", id); } else {set. ADD (ID); }}} Console.WriteLine ($ "Task {++taskcount} completed"); } }}
Maybe some people just care about how to use it later? = = "
Idworker worker = new Idworker (1, 1); //large concurrency, reducing the number of new times can effectively avoid the possibility of duplication
var id = worker. NextID ();
It is possible that the above reduction new some comrades do not quite understand, (⊙o⊙) ..., for example:
If the test code is not changed, change the following sentence:
Full call Demo: (Https://github.com/dunitian/snowflake-net/tree/master/Demo)
Core: (Https://github.com/dunitian/snowflake-net/tree/master/Demo.Core)
A description of the global ID, snowflake (snowflake) algorithm