Cancel rendering

Since v21.7 GroupDocs.Viewer supports tasks cancellation with cancellation token.

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.
cancellationTokenSource.CancelAfter(1000);

// Also you can call Cancel method at any time
//cancellationTokenSource.Cancel();

// Wait for the task to cancel.
Thread.Sleep(2000);

// 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 check this example in our public repository with examples at GitHub.

© Aspose Pty Ltd 2001-2022. All Rights Reserved.