jeikabu / nng.NETCore

MIT License
40 stars 22 forks source link

AsyncBase implementations not freeing allocated nng_ctx #110

Open biocommando opened 1 year ago

biocommando commented 1 year ago

Some classes that extend AsyncBase contain a member field Ctx. The field implements INngCtx which does not implement IDisposable but the actual implementation class NngCtx does. This leads to the implementation never disposing of the Ctx field and leaking memory when the async context is disposed of.

You can reproduce it by running this code. If you run it in Visual Studio using heap profiling, you can see that every 100 ms there will be an allocation originating from nng.dll:

using nng;
var factory = nng.NngLoadContext.Init(new(Path.GetDirectoryName(typeof(Program).Assembly.Location)));
using var repSocket = factory.ReplierOpen().ThenListen("inproc://1").Unwrap();
while (true)
{
  using var repAsyncCtx = repSocket.CreateAsyncContext(factory).Unwrap();
  await Task.Delay(100);
}

image

Adding this line to the while loop makes the allocations dissappear (i.e. memory is freed):

((IDisposable)repAsyncCtx.Ctx).Dispose();