Timeouts

TimeoutMs provides an optional timeout in milliseconds, after which the OCR read operation will be cancelled.

Similar to AbortToken, TimeoutMs also helps with reading large input files in case the program or application becomes stuck.

Please note that the feature is not supported in .NET Framework 4.x.x.

Here is an example of using TimeoutMs in C#:

using System;
using System.Threading;
using System.Threading.Tasks;

namespace OCRExample
{
    class Program
    {
        static async Task Main(string[] args)
        {
            // Timeout duration in milliseconds
            int timeoutMs = 5000;  // 5 seconds

            // Simulate an OCR read with a timeout
            try
            {
                // Call the OCR read operation with a timeout
                await PerformOCRWithTimeout(timeoutMs);
            }
            catch (TimeoutException ex)
            {
                // Handle the timeout exception
                Console.WriteLine("OCR operation timed out: " + ex.Message);
            }
        }

        /// <summary>
        /// Simulates an OCR read operation with a specified timeout.
        /// </summary>
        /// <param name="timeoutMs">The timeout in milliseconds.</param>
        /// <returns>A task representing the asynchronous operation.</returns>
        static async Task PerformOCRWithTimeout(int timeoutMs)
        {
            using (var cts = new CancellationTokenSource())
            {
                // Create a cancellation token that triggers after the timeout duration
                cts.CancelAfter(timeoutMs);

                try
                {
                    // Simulate the OCR read operation
                    await SimulateOCRReadAsync(cts.Token);
                }
                catch (OperationCanceledException)
                {
                    // Re-throw the timeout as a TimeoutException
                    throw new TimeoutException("The OCR operation was cancelled due to timeout.");
                }
            }
        }

        /// <summary>
        /// Simulates an OCR read operation that supports cancellation.
        /// </summary>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>A task representing the asynchronous operation.</returns>
        static async Task SimulateOCRReadAsync(CancellationToken cancellationToken)
        {
            // Simulate a long-running OCR read operation
            await Task.Delay(10000, cancellationToken); // The operation takes 10 seconds
        }
    }
}
using System;
using System.Threading;
using System.Threading.Tasks;

namespace OCRExample
{
    class Program
    {
        static async Task Main(string[] args)
        {
            // Timeout duration in milliseconds
            int timeoutMs = 5000;  // 5 seconds

            // Simulate an OCR read with a timeout
            try
            {
                // Call the OCR read operation with a timeout
                await PerformOCRWithTimeout(timeoutMs);
            }
            catch (TimeoutException ex)
            {
                // Handle the timeout exception
                Console.WriteLine("OCR operation timed out: " + ex.Message);
            }
        }

        /// <summary>
        /// Simulates an OCR read operation with a specified timeout.
        /// </summary>
        /// <param name="timeoutMs">The timeout in milliseconds.</param>
        /// <returns>A task representing the asynchronous operation.</returns>
        static async Task PerformOCRWithTimeout(int timeoutMs)
        {
            using (var cts = new CancellationTokenSource())
            {
                // Create a cancellation token that triggers after the timeout duration
                cts.CancelAfter(timeoutMs);

                try
                {
                    // Simulate the OCR read operation
                    await SimulateOCRReadAsync(cts.Token);
                }
                catch (OperationCanceledException)
                {
                    // Re-throw the timeout as a TimeoutException
                    throw new TimeoutException("The OCR operation was cancelled due to timeout.");
                }
            }
        }

        /// <summary>
        /// Simulates an OCR read operation that supports cancellation.
        /// </summary>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>A task representing the asynchronous operation.</returns>
        static async Task SimulateOCRReadAsync(CancellationToken cancellationToken)
        {
            // Simulate a long-running OCR read operation
            await Task.Delay(10000, cancellationToken); // The operation takes 10 seconds
        }
    }
}
Imports System
Imports System.Threading
Imports System.Threading.Tasks

Namespace OCRExample
	Friend Class Program
		Shared Async Function Main(ByVal args() As String) As Task
			' Timeout duration in milliseconds
			Dim timeoutMs As Integer = 5000 ' 5 seconds

			' Simulate an OCR read with a timeout
			Try
				' Call the OCR read operation with a timeout
				Await PerformOCRWithTimeout(timeoutMs)
			Catch ex As TimeoutException
				' Handle the timeout exception
				Console.WriteLine("OCR operation timed out: " & ex.Message)
			End Try
		End Function

		''' <summary>
		''' Simulates an OCR read operation with a specified timeout.
		''' </summary>
		''' <param name="timeoutMs">The timeout in milliseconds.</param>
		''' <returns>A task representing the asynchronous operation.</returns>
		Private Shared Async Function PerformOCRWithTimeout(ByVal timeoutMs As Integer) As Task
			Using cts = New CancellationTokenSource()
				' Create a cancellation token that triggers after the timeout duration
				cts.CancelAfter(timeoutMs)

				Try
					' Simulate the OCR read operation
					Await SimulateOCRReadAsync(cts.Token)
				Catch e1 As OperationCanceledException
					' Re-throw the timeout as a TimeoutException
					Throw New TimeoutException("The OCR operation was cancelled due to timeout.")
				End Try
			End Using
		End Function

		''' <summary>
		''' Simulates an OCR read operation that supports cancellation.
		''' </summary>
		''' <param name="cancellationToken">The cancellation token.</param>
		''' <returns>A task representing the asynchronous operation.</returns>
		Private Shared Async Function SimulateOCRReadAsync(ByVal cancellationToken As CancellationToken) As Task
			' Simulate a long-running OCR read operation
			Await Task.Delay(10000, cancellationToken) ' The operation takes 10 seconds
		End Function
	End Class
End Namespace
$vbLabelText   $csharpLabel

Explanation

  1. Timeout Configuration:

    • timeoutMs: Specifies the timeout duration in milliseconds—here, it's set to 5000 ms (5 seconds).
  2. Cancellation Token Source:

    • A CancellationTokenSource is used to signal when the operation should be cancelled. The CancelAfter method automatically cancels the operation after the specified timeout.
  3. Simulated OCR Read:

    • The SimulateOCRReadAsync method mimics a long-running operation that can be cancelled through the cancellationToken.
    • If the operation takes longer than specified by timeoutMs, it is cancelled.
  4. Exception Handling:
    • The code covers cases where the OCR operation might get cancelled due to a timeout by throwing a TimeoutException, allowing the caller to handle it as needed.

This explains the primary components of a timeout operation in C#, providing a mechanism to handle operations that might hang or take too long, ensuring better application reliability.