GroupDocs.Conversion supports cancellation of long-running conversion operations using the standard .NET CancellationToken mechanism. This is particularly useful when converting large or complex documents where you need to:
Set a maximum time limit for the conversion operation
Allow users to cancel an ongoing conversion
Implement responsive applications that can abort conversions on demand
Using CancellationToken with classic syntax
To cancel or timeout a conversion operation, follow these steps:
Call the Convert method with the CancellationToken parameter.
Handle the OperationCanceledException to gracefully manage cancellation scenarios.
The following code snippet shows how to set a timeout for a conversion operation:
usingGroupDocs.Conversion;usingGroupDocs.Conversion.Options.Convert;using(Converterconverter=newConverter("sample.dwg")){using(CancellationTokenSourcects=newCancellationTokenSource()){// Auto-cancel after 60 secondscts.CancelAfter(TimeSpan.FromSeconds(60));try{PdfConvertOptionsoptions=newPdfConvertOptions();converter.Convert("converted.pdf",options,cts.Token);}catch(OperationCanceledException){Console.WriteLine("Conversion was cancelled or timed out");}}}
Using CancellationToken with fluent syntax
You can also use fluent syntax to perform cancellable conversions.
The following code snippet shows how to use CancellationToken with fluent syntax:
usingGroupDocs.Conversion;usingGroupDocs.Conversion.Options.Convert;using(CancellationTokenSourcects=newCancellationTokenSource()){// Auto-cancel after 60 secondscts.CancelAfter(TimeSpan.FromSeconds(60));try{FluentConverter.Load("sample.dwg").ConvertTo("converted.pdf").WithOptions(newPdfConvertOptions()).Convert(cts.Token);}catch(OperationCanceledException){Console.WriteLine("Conversion was cancelled or timed out");}}
Manual cancellation
You can also trigger cancellation manually, for example, in response to a user action:
usingGroupDocs.Conversion;usingGroupDocs.Conversion.Options.Convert;CancellationTokenSourcects=newCancellationTokenSource();// Start conversion in a background taskTaskconversionTask=Task.Run(()=>{using(Converterconverter=newConverter("large-document.dwg")){try{PdfConvertOptionsoptions=newPdfConvertOptions();converter.Convert("converted.pdf",options,cts.Token);Console.WriteLine("Conversion completed successfully");}catch(OperationCanceledException){Console.WriteLine("Conversion was cancelled by user");}}});// Simulate user cancellation after 10 secondsThread.Sleep(TimeSpan.FromSeconds(10));cts.Cancel();awaitconversionTask;cts.Dispose();
Was this page helpful?
Any additional feedback you'd like to share with us?
Please tell us how we can improve this page.
Thank you for your feedback!
We value your opinion. Your feedback will help us improve our documentation.
Analyzing your prompt, please hold on...
An error occurred while retrieving the results. Please refresh the page and try again.