kekyo / FlashCap

Independent video frame capture library on .NET/.NET Core and .NET Framework.
Apache License 2.0
203 stars 29 forks source link

Possible leaks in AsyncLock #142

Closed RyanYANG52 closed 7 months ago

RyanYANG52 commented 7 months ago

Hi, @kekyo , I'm looking through your code, https://github.com/kekyo/FlashCap/blob/854186a445e494548480ae0d6b607c1bf009eb57/FlashCap.Core/Internal/AsyncLock.cs#L47

here it registered a cancel callback, but it never dispose even when lock is acquired, ct would hold on to all the tcs until it's cancelled. In my case I create one CancellationTokenSource, only Cancel when the app is closed, if any race condition happen it would add a registration to the linked list inside cts

maybe add something like this:

        if (ct != default)
        {
            var registration = ct.Register(() => tcs.TrySetCanceled());
            tcs.Task.ContinueWith(_ => registration.Dispose(), TaskContinuationOptions.ExecuteSynchronously); // dispose registration after task completion
        }

I see it was done in AsyncEx lib

https://github.com/StephenCleary/AsyncEx/blob/master/src/Nito.AsyncEx.Coordination/AsyncWaitQueue.cs#L82

kekyo commented 7 months ago

Thanks and fixed.