WalletConnectSharp icon indicating copy to clipboard operation
WalletConnectSharp copied to clipboard

Inconsistent Disposal of Asynchronous Operations

Open skibitsky opened this issue 2 years ago • 0 comments

Across various sections of the codebase, the Dispose method fails to properly terminate ongoing asynchronous operations. This oversight leads to unintended lingering tasks, risking resource leaks and unexpected behaviors. A standardized approach to cancel these operations during disposal is needed.

Consider current implementation of HeartBeat.cs as an example.

// ...

public Task Init()                                                 
{                                                                  
    HeartBeatCancellationToken = new CancellationToken();          
                                                                   
    Task.Run(async () =>                                           
    {                                                              
        while (!HeartBeatCancellationToken.IsCancellationRequested)
        {                                                          
            Pulse();                                               
                                                                   
            await Task.Delay(Interval, HeartBeatCancellationToken);
        }                                                          
    }, HeartBeatCancellationToken);                                
                                                                   
    return Task.CompletedTask;                                     
}                                                                  
                                                                   
// ...                                                             
                                                                   
public void Dispose()                                              
{                                                                  
    Events?.Dispose();                                             
}                                                                  

Correct implementation of Dispose should look like so:

public void Dispose()                                              
{        
    HeartBeatCancellationTokenSource?.Cancel();                                                          
    Events?.Dispose();                                             
}    

skibitsky avatar Oct 10 '23 07:10 skibitsky