othercore.mdx 3.0 KB
Newer Older
若汝棋茗 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
---
id: othercore
title: 其他相关功能类
---

## 一、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进制相关
若汝棋茗 已提交
31

若汝棋茗 已提交
32 33 34 35 36 37 38 39 40 41
【将16进制的字符转换为数组】
```csharp
 public static byte[] ByHexStringToBytes(this string hexString, string splite = default)
```
【将16进制的字符转换为int32】
```csharp
 public static int ByHexStringToInt32(this string hexString)
```

## 五、雪花ID生成
若汝棋茗 已提交
42

若汝棋茗 已提交
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
雪花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();
    }
}
```
若汝棋茗 已提交
85 86 87 88 89 90 91 92 93 94

## 七、短时间戳

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

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

若汝棋茗 已提交
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
## 八、读写锁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
}
```
若汝棋茗 已提交
127

若汝棋茗 已提交
128 129 130 131 132
:::tip 提示

**ReadLock**和**WriteLock**均为struct类型,所以几乎不会影响性能。

:::