Cancel viewing with cancellation token

Since 21.7 version GroupDocs.Viewer supports tasks cancellation with cancellation token (for .NET standard only).

Here is the recipe:

You can cancel tasks with these methods:

  • By calling CancelAfter method to cancel task after specified time.
  • By calling Cancel method to cancel the task at any time.

The following code sample shows how to apply the watermark to the output pages.

// Create cancellation token source.
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
// Create (get) cancellation token object.
CancellationToken cancellationToken = cancellationTokenSource.Token;

// Create task and pass token
Task runTask = Task.Run(() =>
    using (Viewer viewer = new Viewer(TestFiles.SAMPLE_DOCX, new ViewerSettings(new GroupDocs.Viewer.Logging.ConsoleLogger())))
        HtmlViewOptions options = HtmlViewOptions.ForEmbeddedResources(pageFilePathFormat);
        options.RenderComments = true;

        viewer.View(options, cancellationToken);
}, cancellationToken);

// Cancel task after 1000 ms.

// Also you can call Cancel method at any time

// Wait for the task to cancel.

// runTask.IsCanceled == true 

Important note: To correctly handle task cancellation you should pass your cancellation token to Task.Run method, otherwise, the flag in runTask.IsCancelled will not equal to true (that indicates task has canceled).

Also following methods in Viewer class support cancellation:

Also you can start this sample on GitHub.

More resources

GitHub Examples

You may easily run the code above and see the feature in action in our GitHub examples:

Free Online App

Along with full-featured .NET library we provide simple but powerful free Apps. You are welcome to view Word, PDF, Excel, PowerPoint documents with free to use online GroupDocs Viewer App.