跳到主要内容
版本:2.0.0

其他相关功能类

定义

命名空间:TouchSocket.Core
程序集:TouchSocket.Core.dll

一、Crc计算

TouchSocket从网上搜集了Crc1-23的计算方法。并封装在了Crc类中。 以最常用的Crc16为例。

byte[] data = new byte[10];
byte[] result = Crc.Crc16(data, 0, data.Length);

二、时间测量器(TimeMeasurer)

功能:封装的Stopwatch,测量运行Action的时间。

TimeSpan timeSpan = TimeMeasurer.Run(() =>
{
Thread.Sleep(1000);
});

三、MD5计算

string str = MD5.GetMD5Hash("TouchSocket");
bool b = MD5.VerifyMD5Hash("TouchSocket",str);

四、16进制相关

【将16进制的字符转换为数组】

 public static byte[] ByHexStringToBytes(this string hexString, string splite = default)

【将16进制的字符转换为int32】

 public static int ByHexStringToInt32(this string hexString)

五、雪花Id生成

雪花Id,会生成long类型的不重复Id。

SnowflakeIDGenerator generator = new SnowflakeIDGenerator(4);
long id=generator.NextID();

六、数据压缩

内部封装了Gzip的压缩。使用静态方法即可完成。


byte[] data = new byte[1024];
new Random().NextBytes(data);

using (ByteBlock byteBlock=new ByteBlock())
{
GZip.Compress(byteBlock,data,0,data.Length);//压缩
var decompressData2 = GZip.Decompress(byteBlock.ToArray());//解压
}


压缩接口 内部还定义了一个IDataCompressor的压缩接口。目的是为了向成熟框架传递压缩方法(例如TcpClient)。 默认配备了一个GZipDataCompressor。可以直接使用。当然大家可以自由扩展其他压缩方法。

class MyDataCompressor : IDataCompressor
{
public byte[] Compress(ArraySegment<byte> data)
{
//此处实现压缩
throw new NotImplementedException();
}

public byte[] Decompress(ArraySegment<byte> data)
{
//此处实现压缩
throw new NotImplementedException();
}
}

七、短时间戳

一般的,时间可由long类型作为唯一时间戳,但是有时候,我们也需要短类型的时间戳(uint),所以您可以使用DateTimeExtensions类实现,或者使用其扩展方法。

uint timestamp= DateTimeExtensions.ConvertTime(DateTime.Now);
timestamp= DateTime.Now.ConvertTime();//扩展方法

八、读写锁using

一般的,我们都会使用ReaderWriterLockSlim读写锁,进行成对的Enter和Exit。所以我们一般会使用下列代码。

ReaderWriterLockSlim lockSlim   = new ReaderWriterLockSlim();
try
{
lockSlim.EnterReadLock();
//do something
}
finally
{
lockSlim.ExitReadLock();
}

但是会显得代码非常臃肿。所以我们可以简化使用using实现。

ReaderWriterLockSlim lockSlim   = new ReaderWriterLockSlim();

using (new ReadLock(lockSlim))
{
//do something
}

using (new WriteLock(lockSlim))
{
//do something
}
提示

ReadLockWriteLock均为struct类型,所以几乎不会影响性能。