Create the Task object. When creating, specify the cancellation token.
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:
usingSystem.Diagnostics;usingSystem.Threading.Tasks;usingSystem.Threading;usingGroupDocs.Viewer;usingGroupDocs.Viewer.Options;// ...// Create cancellation token source.CancellationTokenSourcecancellationTokenSource=newCancellationTokenSource();CancellationTokencancellationToken=cancellationTokenSource.Token;// Create task and pass tokenTaskrunTask=Task.Run(()=>{using(Viewerviewer=newViewer("sample.docx")){HtmlViewOptionsoptions=HtmlViewOptions.ForEmbeddedResources();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);Debug.Assert(runTask.IsCanceled);
ImportsSystem.ThreadingImportsGroupDocs.ViewerImportsGroupDocs.Viewer.Options' ...
ModuleProgramSubMain(argsAsString())' Create cancellation token source.
DimcancellationTokenSourceAsCancellationTokenSource=NewCancellationTokenSource()DimcancellationTokenAsCancellationToken=cancellationTokenSource.Token' Create task and pass token
DimrunTaskAsTask=Task.Run(Sub()UsingviewerAsViewer=NewViewer("sample.docx")DimoptionsAsHtmlViewOptions=HtmlViewOptions.ForEmbeddedResources()options.RenderComments=Trueviewer.View(options,cancellationToken)EndUsingEndSub,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)Debug.Assert(runTask.IsCanceled)EndSubEndModule
sample.docx is the sample file used in this example. Click here to download it.
Note
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: