Cancellation on ExcelFile.Load

The application I’m working on is async and supports cancellation for async operations. The ExcelFile.Load method can be long running, but is not async and doesn’t support cancellation. Is there a recommended approach for handling cancellation if required?

If there isn’t a supported technique for dealing with cancellation, will I run into trouble if I do the following:

  • Create a “wrapper stream” class called CancellationAwareStream that inherits from System.IO.Stream. This CancellationAwareStream will accept a Stream for the .xlsx file and a CancellationToken in its constructor.
  • Close the .xlsx stream from within the CancellationAwareStream if the cancellation token is cancelled.
  • Pass the CancellationAwareStream in to the ExcelSheet.Load method

The implementation surrounding ExcelFile.Load would look something like this:

public Task LoadExcelAsync(string filePath, CancellationToken cancellationToken)
{
    return Task.Run(() =>
    {
        // Open the file stream
        using (var fileStream = File.OpenRead(filePath))
        // Wrap it with the cancellation-aware stream.
        using (var wrapperStream = new CancellationAwareStream(fileStream, cancellationToken))
        {
            // load using the cancellation aware stream.
            var excelFile = ExcelFile.Load(wrapperStream);

            // Process the excelFile as needed...
        }
    }, cancellationToken);
}

Hi,

Unfortunately, I’m not sure how that will work. How exactly will CancellationAwareStream cancel the synchronous work of the underlined stream?

Nevertheless, please check the “Progress Reporting and Cancellation” example:

Last, regarding the async methods, as shown in the above example, the asynchronous execution is currently event-based.
However, starting this year, we have removed support for .NET Framework 3.5. Now, the minimum supported version is 4.6.2, making it easier to incorporate the asynchronous execution with a task-based approach in the future.

Regards,
Mario

1 Like