在转换或加载花费太长时间时使用InterruptMonitor停止转换或加载

可能的使用场景

Aspose.Cells允许你使用InterruptMonitor对象在转换到PDF、HTML等各种格式时在消耗太多时间时停止转换。转换过程通常既使用CPU又使用内存,并且在资源有限时停止它通常是有用的。你可以使用InterruptMonitor既停止转换又停止加载大型工作簿。请使用Workbook.InterruptMonitor属性停止转换,使用LoadOptions.InterruptMonitor属性加载大型工作簿。

在转换或加载花费太长时间时使用InterruptMonitor停止转换或加载

以下示例代码解释了使用 InterruptMonitor 对象的用法。该代码将大型Excel文件转换为PDF。由于这些代码行的原因,转换需要几秒钟(即超过30秒)。

//Access cell J1000000 and add some text inside it.

Cell cell = ws.Cells["J1000000"];

cell.PutValue("This is text.");

正如您所见 J1000000 是XLSX文件中相当远的单元格。但是,WaitForWhileAndThenInterrupt() 方法在10秒后中断转换,程序结束/终止。请使用以下代码执行示例代码。

 new StopConversionOrLoadingUsingInterruptMonitor().TestRun();

示例代码

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
public class StopConversionOrLoadingUsingInterruptMonitor
{
//Output directory
static string outputDir = RunExamples.Get_OutputDirectory();
//Create InterruptMonitor object
InterruptMonitor im = new InterruptMonitor();
//This function will create workbook and convert it to Pdf format
void CreateWorkbookAndConvertItToPdfFormat(object threadObj)
{
Thread monitorThread = (Thread)threadObj;
//Create a workbook object
Workbook wb = new Workbook();
//Assign it InterruptMonitor object
wb.InterruptMonitor = im;
//Access first worksheet
Worksheet ws = wb.Worksheets[0];
//Access cell J1000000 and add some text inside it.
Cell cell = ws.Cells["J1000000"];
cell.PutValue("This is text.");
try
{
//Save the workbook to Pdf format
wb.Save(outputDir + "output_InterruptMonitor.pdf");
//Show successful message
Console.WriteLine("Excel to PDF - Successful Conversion");
//stop monitor thread
monitorThread.Interrupt();
}
catch (Aspose.Cells.CellsException ex)
{
if (ex.Code == ExceptionType.Interrupted)
{
Console.WriteLine("Conversion process is interrupted - Message: " + ex.Message);
}
else
{
throw ex;
}
}
}
//This function will interrupt the conversion process after 10s
void WaitForWhileAndThenInterrupt()
{
try
{
Thread.Sleep(1000 * 10);
im.Interrupt();
}
catch(ThreadInterruptedException e)
{
Console.WriteLine("Monitor thread is interrupted - Message: " + e.Message);
}
}
public void TestRun()
{
Thread monitorThread = new Thread(WaitForWhileAndThenInterrupt);
Thread conversionThread = new Thread(CreateWorkbookAndConvertItToPdfFormat);
monitorThread.Start();
conversionThread.Start(monitorThread);
monitorThread.Join();
conversionThread.Join();
}
public static void Run()
{
new StopConversionOrLoadingUsingInterruptMonitor().TestRun();
Console.WriteLine("StopConversionOrLoadingUsingInterruptMonitor executed successfully.");
}
}