Performance and Asynchronous Processing

A feature that optimizes the conversion process by enabling background operations and asynchronous execution, ensuring that number-to-word conversions do not block the main application thread.

Overview

The Performance & Asynchronous Processing feature provides properties and methods to perform number conversions asynchronously. This is particularly useful for enhancing UI responsiveness in WinForms applications by offloading potentially heavy conversion computations to background threads. Key elements include toggling asynchronous processing via EnableAsync, controlling operation timeouts with AsyncTimeout, and invoking asynchronous conversions through the NumberToWordsAsync method.


Key Points

Aspect
Description

Asynchronous Processing

The EnableAsync property enables background processing, allowing conversions to run without blocking the UI thread.

Timeout Control

The AsyncTimeout property defines the maximum wait time (in milliseconds) before an async conversion is cancelled, ensuring that long-running operations do not hang the application.

Async Conversion Method

The NumberToWordsAsync method performs the conversion in a background task, providing improved performance for heavy or repeated conversion requests.

Code Example

// Initialize the control for asynchronous processing
var humanizer = new SiticoneHumanizerInt();

// Enable asynchronous processing for conversions
humanizer.EnableAsync = true;

// Set a custom timeout for asynchronous operations (e.g., 3000 milliseconds)
humanizer.AsyncTimeout = 3000;

// Asynchronously convert a number to words
async Task PerformAsyncConversion()
{
    try
    {
        string result = await humanizer.NumberToWordsAsync(123456);
        Console.WriteLine("Asynchronous conversion result: " + result);
    }
    catch (TimeoutException ex)
    {
        Console.WriteLine("Async conversion timed out: " + ex.Message);
    }
    catch (Exception ex)
    {
        Console.WriteLine("Error during async conversion: " + ex.Message);
    }
}

Best Practices

Practice
Recommendation

Use Async in UI Applications

When integrating with WinForms or other UI applications, use asynchronous conversion to keep the interface responsive while heavy computations are performed in the background.

Set Appropriate Timeouts

Adjust the AsyncTimeout property based on the expected workload and environment to prevent indefinite waits or premature cancellations.

Implement Robust Exception Handling

Always wrap asynchronous calls in try-catch blocks to handle TimeoutException and other exceptions that may be thrown during background processing.

Code Example

// Example: Handling exceptions in an asynchronous conversion
async Task ExecuteConversionAsync()
{
    try
    {
        string conversionResult = await humanizer.NumberToWordsAsync(98765);
        Console.WriteLine("Async conversion successful: " + conversionResult);
    }
    catch (TimeoutException tex)
    {
        Console.WriteLine("Conversion timed out: " + tex.Message);
    }
    catch (Exception ex)
    {
        Console.WriteLine("Conversion failed: " + ex.Message);
    }
}

Common Pitfalls

Pitfall
Explanation

Blocking the UI Thread

Not using the asynchronous method (NumberToWordsAsync) in UI applications can cause the UI to freeze during heavy conversions.

Inadequate Timeout Settings

Setting an overly short or long AsyncTimeout may either cancel valid conversions prematurely or allow long-running tasks to degrade application performance.

Unhandled Exceptions in Async Methods

Failing to implement proper exception handling around asynchronous calls may result in unhandled exceptions, causing the application to crash or behave unpredictably.

Code Example

// Incorrect: Calling the conversion synchronously on the UI thread in a WinForms app can lead to UI freezing
humanizer.EnableAsync = false;
humanizer.Number = 123456; // Synchronous conversion on the UI thread
Console.WriteLine("Synchronous conversion: " + humanizer.Words);

Usage Scenarios

Scenario
How It Works

Responsive UI Applications

In WinForms apps, use asynchronous conversion to perform number-to-word conversions without interrupting user interactions or blocking the main thread.

Background Data Processing

Offload heavy numerical conversions to background tasks in data processing applications, ensuring that the primary workflow remains unaffected by computational delays.

Batch Processing

When converting large volumes of numbers, asynchronous processing can significantly reduce the perceived delay by processing tasks concurrently.

Code Example

// Example: Using asynchronous conversion to update a UI control in a WinForms application
async void ConvertAndDisplayNumber()
{
    try
    {
        string conversion = await humanizer.NumberToWordsAsync(54321);
        // Assume lblResult is a label on the form
        lblResult.Text = conversion;
    }
    catch (Exception ex)
    {
        MessageBox.Show("Conversion error: " + ex.Message);
    }
}

Real Life Usage Scenarios

Scenario
Explanation

Financial Dashboards

In applications where real-time financial data is displayed, asynchronous conversion ensures that updates occur smoothly without impacting the user experience.

Educational Software

Applications that convert large datasets (e.g., converting statistical data to words) benefit from asynchronous processing to maintain performance and responsiveness.

Report Generation

When generating detailed reports that involve numerous conversions, asynchronous processing allows the report to be built incrementally while the UI remains responsive.

Code Example

// Example: Asynchronously processing multiple conversions in a report generation tool
async Task ProcessReportAsync(IEnumerable<decimal> numbers)
{
    foreach (var num in numbers)
    {
        try
        {
            string words = await humanizer.NumberToWordsAsync(num);
            // Append the conversion result to the report (assume AppendToReport is a method to update the report)
            AppendToReport($"{num} in words: {words}");
        }
        catch (Exception ex)
        {
            AppendToReport($"Error converting {num}: {ex.Message}");
        }
    }
}

Troubleshooting Tips

Tip
Details

Verify Async Settings

Ensure that EnableAsync is set to true and that AsyncTimeout is configured appropriately to avoid unnecessary timeouts or performance issues.

Monitor Application Responsiveness

Use profiling tools to monitor the UI thread for any potential blocks when asynchronous operations are in progress, and adjust settings accordingly.

Log Detailed Error Information

Implement logging within asynchronous methods to capture detailed error information, which can be invaluable when diagnosing timeouts or other exceptions during background processing.

Code Example

// Example: Logging errors in an asynchronous conversion
humanizer.OnError += (sender, e) =>
{
    // Log error details for further analysis
    Console.WriteLine($"Error in async operation {e.Operation}: {e.Exception}");
};

Review

Aspect
Consideration

Responsiveness Improvement

Asynchronous conversion significantly improves application responsiveness by offloading heavy computations from the main thread.

Flexibility and Control

The ability to toggle asynchronous processing and customize timeouts provides developers with fine-grained control over performance aspects.

Integration Complexity

Although asynchronous methods introduce additional complexity (e.g., exception handling), the benefits for UI responsiveness and overall performance are substantial.


Summary

Summary Point
Description

Asynchronous Conversion

Offloads heavy number-to-word conversion tasks to background threads using the NumberToWordsAsync method, thereby maintaining UI responsiveness.

Customizable Timeout

The AsyncTimeout property allows developers to define a maximum wait period for conversions, ensuring that long-running tasks do not degrade performance.

Developer-Friendly Integration

With simple property settings and clear code examples, integrating asynchronous processing into WinForms applications is straightforward and effective.

Final Integration Example

using System;
using System.Threading.Tasks;
using System.Windows.Forms;
using SiticoneNetFrameworkUI;

namespace DemoPerformanceAsync
{
    public partial class MainForm : Form
    {
        private readonly SiticoneHumanizerInt humanizer;

        public MainForm()
        {
            InitializeComponent();
            humanizer = new SiticoneHumanizerInt();

            // Subscribe to conversion and error events
            humanizer.OnNumbersChanged += (sender, e) =>
            {
                // Update a UI control on successful conversion
                lblConversionResult.Text = e.Words;
            };

            humanizer.OnError += (sender, e) =>
            {
                // Log or display error information
                MessageBox.Show($"Error in {e.Operation}: {e.Exception.Message}", "Conversion Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            };

            // Enable asynchronous processing and set timeout
            humanizer.EnableAsync = true;
            humanizer.AsyncTimeout = 5000;
        }

        private async void btnConvert_Click(object sender, EventArgs e)
        {
            try
            {
                // Start asynchronous conversion when button is clicked
                string result = await humanizer.NumberToWordsAsync(Convert.ToDecimal(txtNumber.Text));
                lblConversionResult.Text = result;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Conversion failed: " + ex.Message);
            }
        }
    }
}

This comprehensive documentation provides developers with detailed guidance on integrating and utilizing the Performance & Asynchronous Processing feature in their .NET WinForms applications. The key points, best practices, common pitfalls, and real-life usage scenarios, along with extensive code examples, ensure a smooth integration and effective performance optimization.

Last updated