iBicha / UnityYoutubePlayer

Play YouTube videos in Unity
The Unlicense
339 stars 64 forks source link

ArgumentNullException in SendWebRequestAsync method when using CancellationToken #124

Closed SeongSeopLIm closed 5 months ago

SeongSeopLIm commented 5 months ago

Hi,

I encountered an error in the SendWebRequestAsync method when calling it with a CancellationToken. The following error occurs:

ArgumentNullException: Value cannot be null. Parameter name: _unity_self YoutubePlayer.Extensions.UnityWebRequestExtensions+<>c__DisplayClass0_0.<SendWebRequestAsync>b__1 (System.Object obj) (at ./Packages/com.ibicha.youtube-player/Runtime/Extensions/UnityWebRequestExtensions.cs:40) System.Threading.CancellationCallbackInfo.ExecutionContextCallback (System.Object obj) (at <dc753a1061284f8e971ee88ee4826eee>:0)

I believe this issue is caused by not properly unregistering the CancellationTokenRegistration. Here is the original code and my proposed fix:

    cancellationToken.Register(obj =>
    {
        tcs.TrySetCanceled(cancellationToken);
        var request = (UnityWebRequest)obj;
        request.Abort();
    }, request);

    var op = request.SendWebRequest();
    op.completed += OnComplete;

    return await tcs.Task;

Proposed Fix:

    var op = request.SendWebRequest();

    var registration = cancellationToken.Register(obj =>
    {
        tcs.TrySetCanceled(cancellationToken);
        op.completed -= OnComplete;
        var request = (UnityWebRequest)obj;
        request.Abort();
    }, request);

    op.completed += OnComplete;
    var webRequest = await tcs.Task;

    if (registration != null)
    {
        registration.Dispose(); 
    }

    return webRequest;

Please review the proposed changes

Thank you

iBicha commented 5 months ago

Thanks for catching this, your fix makes sense to me

iBicha commented 5 months ago

Fixed in 3.3.1