C生成唯一时间戳ID代码分享

36次阅读

共计 1774 个字符,预计需要花费 5 分钟才能阅读完成。

///
/// 时刻戳 ID
///
publicclassTimestampID
{
privatelong_lastTimestamp;
privatelong_sequence;// 计数从零开始
privatereadonlyDateTime?_initialDateTime;
privatestaticTimestampID_timestampID;
privateconstintMAX_END_NUMBER=9999;
privateTimestampID(DateTime?initialDateTime)C#
{
_initialDateTime=initialDateTime;
}
///
/// 获取单个实例对象
///
/// 开始时刻,与当前时刻做个相差取时刻戳
///
publicstaticTimestampIDGetInstance(DateTime?initialDateTime=null)
{
if(_timestampID==null)Interlocked.CompareExchange(ref_timestampID,newTimestampID(initialDateTime),null);
return_timestampID;
}
///
/// 开始时刻,作用时刻戳的相差
///
protectedDateTimeInitialDateTime
{
get
{
if(_initialDateTime==null||_initialDateTime.Value==DateTime.MinValue)returnnewDateTime(1970,1,1,0,0,0,DateTimeKind.Utc);
return_initialDateTime.Value;
}
}
///
/// 获取时刻戳 ID
///
///
publicstringGetID()
{
longtemp;
vartimestamp=GetUniqueTimeStamp(_lastTimestamp,outtemp);
return$”{timestamp}{Fill(temp)}”;
}
privatestringFill(longtemp)
{
varnum=temp.ToString();
IListchars=newList();
for(inti=0;i<MAX_END_NUMBER.ToString().Length-num.Length;i++)
{
chars.Add(‘0’);
}
returnnewstring(chars.ToArray())+num;
}
///
/// 获取一个时刻戳字符串
///
///
publiclongGetUniqueTimeStamp(longlastTimeStamp,outlongtemp)
{
lock(this)
{
temp=1;
vartimeStamp=GetTimestamp();
if(timeStamp==_lastTimestamp)
{
_sequence=_sequence+1;
temp=_sequence;
if(temp>=MAX_END_NUMBER)
{
timeStamp=GetTimestamp();
_lastTimestamp=timeStamp;
temp=_sequence=1;
}
}
else
{
_sequence=1;
_lastTimestamp=timeStamp;
}
returntimeStamp;
}
}
///
///
///
///
privatelongGetTimestamp()
{
if(InitialDateTime>=DateTime.Now)thrownewException(“开始时刻比当前时刻还大,不合理”);
varts=DateTime.UtcNow-InitialDateTime;
return(long)ts.TotalMilliseconds;
}
}

正文完
 0