[]
        
(Showing Draft Content)

Cancel Template Processing

GcExcel allows you to cancel ProcessTemplate method by using an overload of ProcessTemplate method that takes a parameter of CancellationToken type. The cancellation is thread-safe, i.e., the cancellation request is sent by a thread that does not own the workbook. You can use the following methods of CancellationTokenSource to send signals to CancellationToken:

Methods

Description

Cancel

Cancels the method immediately.

CancelAfter

Cancels the method after specific delay time.

Dispose

Releases all resources used by current instance.

The overload of ProcessTemplate method cancels the process when the following conditions are met:

  • The CancellationTokenSource of CancellationToken requests the cancellation.

  • The internal data structures of ProcessTemplate method are consistent, i.e., it is safe to continue using the workbook object when the cancellation request is handled.

  • ProcessTemplate method is in progress.

Note: You must decide whether to accept the partially expanded template or revert to the previous state. If you want to revert to the previous state, you must serialize the workbook before calling the ProcessTemplate method and then deserialize after canceling the operation.

Refer to the following example code to cancel template processing on request or after a timeout is reached:

// Create a new workbook.
var workbook = new GrapeCity.Documents.Excel.Workbook();

// Load template file from resource.
workbook.Open("Template_SalesDataGroup_DataTable.xlsx");

Console.WriteLine("Creating test data.");

// Add data to DataTable.
var datasource = new System.Data.DataTable();
datasource.Columns.Add(new DataColumn("Area", typeof(string)));
datasource.Columns.Add(new DataColumn("City", typeof(string)));
datasource.Columns.Add(new DataColumn("Category", typeof(string)));
datasource.Columns.Add(new DataColumn("Name", typeof(string)));
datasource.Columns.Add(new DataColumn("Revenue", typeof(double)));

var areas = new[] { "North America", "South America" };
var cities = new[] { "Chicago", "New York", "Santiago", "Quito", "Fremont", "Buenos Aires", "Medillin", "Minnesota" };
var categories = new[] { "Consumer Electronics", "Mobile" };
var category1NamePrefixes = new[] { "Bose ", "Canon ", "Haier ", "IFB ", "Mi ", "Sennheiser " };
var category2NamePrefixes = new[] { "iPhone ", "OnePlus ", "Redmi ", "Samsung " };

Random rand = new Random();
var rows = datasource.Rows;

// You can increase the loop count if the demo is too fast on your computer.
for (var i = 0; i < 50000; i++)
{
    var area = areas[rand.Next(0, areas.Length)];
    var city = cities[rand.Next(0, cities.Length)];
    var categoryId = rand.Next(0, categories.Length);
    var category = categories[categoryId];
    var names = (categoryId == 0) ? category1NamePrefixes : category2NamePrefixes;
    var name = names[rand.Next(0, names.Length)] + rand.Next(10, 10000).ToString();
    var revenue = rand.Next(10000, 100000);
    rows.Add(area, city, category, name, revenue);
}

// Add template global settings.
workbook.Names.Add("TemplateOptions.KeepLineSize", "true");

// Add data source.
workbook.AddDataSource("ds", datasource);

// Cancel data source binding when cancel key is pressed or timeout is reached.
using (CancellationTokenSource cancellation = new CancellationTokenSource())
{
    void cancelHandler(object sender, ConsoleCancelEventArgs e)
    {
        // Exit the process.
        e.Cancel = true;

        // Prevent entering cancelHandler when ProcessTemplate is completed or canceled.
#if NETCOREAPP3_0_OR_GREATER
        Console.CancelKeyPress -= cancelHandler;
#endif
        // Cancel when cancel key is pressed.
        cancellation.Cancel();
    };
    Console.CancelKeyPress += cancelHandler;

    // Cancel when timeout is reached.
    cancellation.CancelAfter(TimeSpan.FromSeconds(10));
    Console.WriteLine("Start ProcessTemplate.");
    try
    {
        workbook.ProcessTemplate(cancellation.Token);
        Console.WriteLine("ProcessTemplate finished.");
    }
    catch (OperationCanceledException ex) when (ex.CancellationToken == cancellation.Token)
    {
        Console.WriteLine("ProcessTemplate was canceled.");
    }

    // Prevent entering cancelHandler when ProcessTemplate is completed or canceled.
#if NETCOREAPP3_0_OR_GREATER
    Console.CancelKeyPress -= cancelHandler;
#endif
}

// Save the workbook.
workbook.Save("CancelTemplateProcessing.xlsx");