Cancel rendering

Since the 21.7 version, GroupDocs.Viewer supports task cancellation using the cancellation token.

To cancel a task, follow these steps:

  1. Create the CancellationTokenSource object.
  2. Create the CancellationToken object.
  3. Create the Task object. When creating, specify the cancellation token.
  4. Cancel the task.

You can cancel tasks using one of the following methods:

  • To cancel the task in a specified time, call the CancelAfter method.
  • To cancel the task at any time, call the Cancel method.

The following code snippet shows how to cancel a task:

// 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();
        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 

If runTask.IsCancelled is true, then the task has been canceled.

To properly handle task cancellation, pass a cancellation token to the Task.Run method. Otherwise, runTask.IsCancelled is not true.

The following methods of the Viewer class also support cancellation:

You can also view the example in our public GitHub repository .