gpt4 book ai didi

c# - ScopeLock 模式 : Struct or Class?

转载 作者:太空宇宙 更新时间:2023-11-03 14:49:36 26 4
gpt4 key购买 nike

我习惯于使用“Using”语句实现一些作用域锁定模式。

例子:

ReaderWriterLockSlim _storageLocker
using (_storageLocker.LockRead())
{
// do suff
}

在此示例中,扩展方法 LockRead 创建了一个特定的 IDisposable 对象,该对象将在构造中锁定并在释放时释放。

/// <summary>
/// Scope lock pattern that lock the current <see cref="ReaderWriterLockSlim"/> in read mode
/// </summary>
public static IDisposable LockRead(this ReaderWriterLockSlim locker, TimeSpan timeout = default(TimeSpan))
{
if (timeout == default(TimeSpan))
timeout = s_defaultTimeout;

var isLocked = locker.TryEnterReadLock(timeout);

if (isLocked)
return new ScopeLockAction<ReaderWriterLockSlim>(l => l.ExitReadLock(), locker);

return Disposable.Disposed;
}

这种模式比 try/Finally 更有用也更清晰,但遗憾的是每次锁定时它都会创建一个新实例。

ScopeLockAction 正确实现了 IDispose 模式并调用了 GC.SuppressFinalizer() 来稍微优化回收。

我知道 .NET 垃圾收集器实现了一些回收机制,允许他为 future 的相同类型实例重用分配的空间。

我的问题是:

  • 当你有一个固定大小的小实例,经常创建和处理,并且只与 using 语句一起使用(这意味着没有装箱),使用 class 是否更高效> 还是 struct

  • 有什么区别吗?

  • 有没有办法通知垃圾收集器它可以为另一个相同类型的实例回收实例空间?

最佳答案

来自answer在后What are the uses of "using" in C# :

The reason for the "using" statement is to ensure that the object is disposed as soon as it goes out of scope, and it doesn't require explicit code to ensure that this happens.

结构是值类型,类是引用类型,我认为,使用“using”语句并不重要,因为它一旦超出范围就会被销毁。
您可以在 Finalize/Dispose pattern in C# 中找到一些关于使用 IDispose/Finalize 东西的很好的讨论。

关于c# - ScopeLock 模式 : Struct or Class?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52334962/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com