Manually unpinning a byte[] in C#?

后端 未结 1 732
一生所求
一生所求 2021-01-21 09:00

In the following code, it seems that the client.Connect.Receive is pinning the \"byte[] result\" permanently, causing the memory to never be freed (as it\'s always pinned). I\'

相关标签:
1条回答
  • 2021-01-21 09:24

    You can pin/unpin it yourself, thusly:

    //Pin it 
    GCHandle myArrayHandle = GCHandle.Alloc(result,GCHandleType.Pinned);
    //use array
    while (r < length)
    {
        int bytes = client.Client.Receive(result, r, length - r, SocketFlags.None);
        r += bytes;
    }
    //Unpin it
    myArrayHandle.Free();
    

    But I'd personally be pretty surprised that client.Connect.Receive pins it "for all time". I've used it before (as I'm sure many have) and not run into an issue of this type. Alternately, if you're certain that's the problem, then instead of allocating a new result array each time, you can re-use one across the entire while loop (allocate it up where you start the listener, and only use lenbytes bytes each time).

    0 讨论(0)
提交回复
热议问题