Files
TouchSocket/handbook/docs/othercore.mdx
2023-08-06 14:55:38 +08:00

140 lines
3.2 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
id: othercore
title: 其他相关功能类
---
### 定义
命名空间TouchSocket.Core <br/>
程序集:[TouchSocket.Core.dll](https://www.nuget.org/packages/TouchSocket.Core)
## 一、Crc计算
**TouchSocket**从网上搜集了Crc1-23的计算方法。并封装在了Crc类中。
以最常用的Crc16为例。
```csharp
byte[] data = new byte[10];
byte[] result = Crc.Crc16(data, 0, data.Length);
```
## 二、时间测量器TimeMeasurer
功能封装的Stopwatch测量运行Action的时间。
```csharp
TimeSpan timeSpan = TimeMeasurer.Run(() =>
{
Thread.Sleep(1000);
});
```
## 三、MD5计算
```csharp
string str = MD5.GetMD5Hash("TouchSocket");
bool b = MD5.VerifyMD5Hash("TouchSocket",str);
```
## 四、16进制相关
【将16进制的字符转换为数组】
```csharp
public static byte[] ByHexStringToBytes(this string hexString, string splite = default)
```
【将16进制的字符转换为int32】
```csharp
public static int ByHexStringToInt32(this string hexString)
```
## 五、雪花ID生成
雪花ID会生成long类型的不重复ID。
```csharp
SnowflakeIDGenerator generator = new SnowflakeIDGenerator(4);
long id=generator.NextID();
```
## 六、数据压缩
内部封装了Gzip的压缩。使用静态方法即可完成。
```csharp
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。可以直接使用。当然大家可以自由扩展其他压缩方法。
```csharp
class MyDataCompressor : IDataCompressor
{
public byte[] Compress(ArraySegment<byte> data)
{
//此处实现压缩
throw new NotImplementedException();
}
public byte[] Decompress(ArraySegment<byte> data)
{
//此处实现压缩
throw new NotImplementedException();
}
}
```
## 七、短时间戳
一般的时间可由long类型作为唯一时间戳但是有时候我们也需要短类型的时间戳uint所以您可以使用**DateTimeExtensions**类实现,或者使用其扩展方法。
```csharp
uint timestamp= DateTimeExtensions.ConvertTime(DateTime.Now);
timestamp= DateTime.Now.ConvertTime();//扩展方法
```
## 八、读写锁using
一般的,我们都会使用**ReaderWriterLockSlim**读写锁进行成对的Enter和Exit。所以我们一般会使用下列代码。
```csharp
ReaderWriterLockSlim lockSlim = new ReaderWriterLockSlim();
try
{
lockSlim.EnterReadLock();
//do something
}
finally
{
lockSlim.ExitReadLock();
}
```
但是会显得代码非常臃肿。所以我们可以简化使用using实现。
```csharp
ReaderWriterLockSlim lockSlim = new ReaderWriterLockSlim();
using (new ReadLock(lockSlim))
{
//do something
}
using (new WriteLock(lockSlim))
{
//do something
}
```
:::tip 提示
**ReadLock**和**WriteLock**均为struct类型所以几乎不会影响性能。
:::