Код: Выделить всё
protected virtual void Dispose(bool disposing)
{
if (_disposed)
{
return;
}
if (disposing)
{
// TODO: dispose managed state (managed objects).
}
// TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
// TODO: set large fields to null.
_disposed = true;
}
Код: Выделить всё
using System.Runtime.InteropServices;
using Whatever.Extensions;
namespace XYZ.Extensions;
public sealed class NativeMemory : DisposableAsync where T : unmanaged
{
public unsafe NativeMemory(uint count, uint alignment = 1)
{
ArgumentOutOfRangeException.ThrowIfZero(alignment);
Length = count * (uint)sizeof(T);
Pointer = (nint)NativeMemory.AlignedAlloc(Length, alignment);
Manager = new NativeMemoryManager((T*)Pointer, (int)Length);
Manager.Memory.Span.Clear();
}
public NativeMemoryManager Manager { get; }
public uint Length { get; }
public nint Pointer { get; }
protected override ValueTask DisposeAsyncCore()
{
DisposeNative();
return ValueTask.CompletedTask;
}
protected override void DisposeNative()
{
DisposePointer();
}
private unsafe void DisposePointer()
{
NativeMemory.AlignedFree(Pointer.ToPointer());
}
}
Код: Выделить всё
using System;
#nullable disable
namespace Whatever.Extensions
{
public abstract class Disposable : IDisposable
{
protected bool IsDisposed { get; set; }
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize((object) this);
}
protected virtual void Dispose(bool disposing)
{
if (this.IsDisposed)
return;
this.DisposeNative();
if (disposing)
this.DisposeManaged();
this.IsDisposed = true;
}
protected virtual void DisposeManaged() { }
protected virtual void DisposeNative() { }
~Disposable() => this.Dispose(false);
}
}
Код: Выделить всё
using System;
using System.Threading.Tasks;
#nullable enable
namespace Whatever.Extensions
{
public abstract class DisposableAsync : Disposable, IAsyncDisposable
{
public async ValueTask DisposeAsync()
{
DisposableAsync disposableAsync = this;
await disposableAsync.DisposeAsyncCore().ConfigureAwait(false);
GC.SuppressFinalize((object) disposableAsync);
}
protected virtual async ValueTask DisposeAsyncCore()
{
await new ValueTask().ConfigureAwait(false);
}
}
}
Вопрос:< /p>
При удалении NativeMemory следует рассматривать его как управляемый или неуправляемый?
Подробнее здесь: https://stackoverflow.com/questions/787 ... in-the-end