SapNwRfc icon indicating copy to clipboard operation
SapNwRfc copied to clipboard

RFC Server - delegate gets garbage collected

Open tom-j-irvine opened this issue 2 years ago • 3 comments

I'm having an issue trying to use the RFC Server functionality. I'm able to launch the server and listen for calls. However, after some time, the world comes crashing down with the following fatal error:

Process terminated. A callback was made on a garbage collected delegate of type 'SapNwRfcDotNet!SapNwRfc.Internal.Interop.RfcInterop+RfcServerFunction::Invoke'.

Initially, I would run into this when receiving some larger function calls (after about 4 or 5 calls), but then I realized I could reproduce it with a higher number of smaller calls. So, I believe the larger calls simply trigger the GC sooner.

This link seems to describe something similar where the managed code isn't holding onto the delegate so it gets collected: https://stackoverflow.com/questions/6193711/call-has-been-made-on-garbage-collected-delegate-in-c

I may try to look closer at it myself (though, I don't know a whole lot about this interop stuff), but wanted to open this issue in case it makes more sense to one of you. Thanks.

tom-j-irvine avatar Jan 19 '22 22:01 tom-j-irvine

Thanks for the report! I can reproduce the issue with this testcase:

var connectionPool = new SapConnectionPool(clientParameters);
var pooledConnection = new SapPooledConnection(connectionPool);

SapServer.InstallGenericServerFunctionHandler(
    (string functionName, SapAttributes attributes) => pooledConnection.GetFunctionMetadata(functionName),
    (ISapServerConnection connection, ISapServerFunction function) => { }
);

using (var server = SapServer.Create(serverParameters))
{
    server.Launch();

    while (true)
    {
        // force GC to collect unreferenced code like the generic function delegates
        GC.Collect();
        GC.WaitForPendingFinalizers();

        await Task.Delay(500);
    }
}

I have added the fix to my existing PR https://github.com/huysentruitw/SapNwRfc/pull/53 in commit https://github.com/huysentruitw/SapNwRfc/pull/53/commits/65dfaa8caccb78683fd9128eb33571cd7a6a23c8

campersau avatar Jan 20 '22 09:01 campersau

Thank you very much for the quick turnaround. I have confirmed that this resolves the issue I was having.

tom-j-irvine avatar Jan 20 '22 15:01 tom-j-irvine

@campersau thanks for this and sorry for the huge delay at my end. Can you create a fix for this in a separate PR?

huysentruitw avatar Aug 23 '22 19:08 huysentruitw