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 fromSystem.IO.Stream
. ThisCancellationAwareStream
will accept aStream
for the.xlsx
file and aCancellationToken
in its constructor. - Close the
.xlsx
stream from within theCancellationAwareStream
if the cancellation token is cancelled. - Pass the
CancellationAwareStream
in to theExcelSheet.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);
}