---
description: >-
  This feature provides methods to control the spinner's operation and events to
  notify consumers of changes in state and progress.
---

# General Control Methods & Events

## Overview

The SiticoneLoadingSpinner control offers a range of methods and events that allow developers to start, stop, reset, and configure the spinner animation, as well as integrate background tasks seamlessly. This section documents each method and event along with usage examples, tables for clarification, key points, best practices, common pitfalls, usage scenarios, and a review summary.

***

### Methods & Events Detailed

Below is a table summarizing the available methods and events, their descriptions, and parameters where applicable.

| **Method/Event**                                                      | **Description**                                                                                                                 | **Parameters / Return Value**                                                        |
| --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ |
| Start()                                                               | Starts the spinner animation.                                                                                                   | None                                                                                 |
| Stop()                                                                | Stops the spinner animation.                                                                                                    | None                                                                                 |
| Reset()                                                               | Resets the spinner state to its initial configuration.                                                                          | None                                                                                 |
| Configure(Action configuration)                                       | Applies multiple configuration changes at once, ensuring smoother initialization.                                               | A delegate that accepts an instance of SiticoneLoadingSpinner for configuration.     |
| RunWorkerAsync(DoWorkEventHandler workHandler)                        | Initiates a background task using a synchronous DoWork event handler, starting the spinner automatically.                       | A DoWorkEventHandler delegate that defines the background task work.                 |
| RunWorkerAsync(Func\<IProgress, CancellationToken, Task> workHandler) | Initiates an asynchronous background task with progress reporting and cancellation support, starting the spinner automatically. | A function that accepts IProgress and CancellationToken, and returns a Task.         |
| CancelAsync()                                                         | Cancels a currently running background task.                                                                                    | None                                                                                 |
| SpinnerStateChanged (Event)                                           | Raised when the spinner starts or stops, allowing consumers to react to state changes.                                          | EventArgs of type SpinnerStateEventArgs containing the running state (true/false).   |
| RotationCompleted (Event)                                             | Raised each time the spinner completes a full rotation.                                                                         | EventArgs (typically empty).                                                         |
| ProgressChanged (Event)                                               | Occurs when progress is updated from the background worker.                                                                     | Standard ProgressChangedEventArgs, with progress percentage details.                 |
| WorkCompleted (Event)                                                 | Occurs when the background worker has completed its task.                                                                       | RunWorkerCompletedEventArgs, with information about task completion or cancellation. |

***

### Code Examples & Integration Samples

#### Starting, Stopping, and Resetting the Spinner

```csharp
// Create an instance of the spinner control.
var spinner = new SiticoneLoadingSpinner();

// Start the spinner animation.
spinner.Start();

// ... perform some tasks

// Stop the spinner animation.
spinner.Stop();

// Reset the spinner to its initial state.
spinner.Reset();
```

#### Configuring Multiple Properties

The `Configure` method lets you apply a series of configuration settings in one call.

```csharp
spinner.Configure(s =>
{
    s.NumberOfSpokes = 16;
    s.SpokeThickness = 3;
    s.SpinnerColor = Color.MediumSeaGreen;
    s.RotationSpeed = 50;
});
```

#### Using Background Worker Methods

**Synchronous Background Task Integration**

```csharp
spinner.RunWorkerAsync((sender, e) =>
{
    // Long running work.
    for (int i = 0; i <= 100; i++)
    {
        // Report progress back to the control.
        (sender as BackgroundWorker)?.ReportProgress(i);
        Thread.Sleep(50); // Simulate work.
    }
});
```

**Asynchronous Background Task Integration with Cancellation**

```csharp
spinner.RunWorkerAsync(async (progress, token) =>
{
    for (int i = 0; i <= 100; i++)
    {
        if (token.IsCancellationRequested)
            token.ThrowIfCancellationRequested();

        // Report progress.
        progress.Report(i / 100.0);
        await Task.Delay(50, token); // Simulate async work.
    }
});
```

To cancel the background task:

```csharp
// Cancel the running background task.
spinner.CancelAsync();
```

#### Handling Spinner Events

Subscribe to events to respond to spinner state changes, rotation completions, or background worker progress updates.

```csharp
// Subscribe to spinner state changes.
spinner.SpinnerStateChanged += (s, e) =>
{
    Console.WriteLine("Spinner running: " + e.IsRunning);
};

// Subscribe to rotation completed events.
spinner.RotationCompleted += (s, e) =>
{
    Console.WriteLine("A full rotation has been completed.");
};

// Subscribe to background progress updates.
spinner.ProgressChanged += (s, e) =>
{
    Console.WriteLine("Progress: " + e.ProgressPercentage + "%");
};

// Subscribe to background work completion.
spinner.WorkCompleted += (s, e) =>
{
    if (e.Cancelled)
        Console.WriteLine("Background work was cancelled.");
    else if (e.Error != null)
        Console.WriteLine("Error occurred: " + e.Error.Message);
    else
        Console.WriteLine("Background work completed successfully.");
};
```

***

### Key Points

| **Point**              | **Details**                                                                               |
| ---------------------- | ----------------------------------------------------------------------------------------- |
| Control Methods        | Use Start(), Stop(), and Reset() to manage the spinner lifecycle.                         |
| Configuration          | The Configure() method enables batch configuration for smoother initialization.           |
| Background Integration | Two overloads of RunWorkerAsync allow both synchronous and asynchronous background tasks. |
| Event Notifications    | Events such as SpinnerStateChanged and RotationCompleted allow responsive UI updates.     |
| Cancellation Support   | Use CancelAsync() to gracefully terminate a background task in progress.                  |

***

### Best Practices

| **Practice**               | **Recommendation**                                                                                                         |
| -------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
| Managing Spinner Lifecycle | Always call Stop() or Reset() when the spinner is no longer needed to free up resources.                                   |
| Batch Configuration        | Use the Configure() method to change multiple properties at once, ensuring that the UI is updated only once after changes. |
| Handling Background Tasks  | Always check for cancellation and handle exceptions in background tasks.                                                   |
| Event Subscription         | Unsubscribe from events when the control is disposed or no longer needed to prevent memory leaks.                          |
| UI Responsiveness          | Avoid long blocking operations on the UI thread; offload work to background tasks using the provided methods.              |

***

### Common Pitfalls

| **Pitfall**                                     | **Solution**                                                                                          |
| ----------------------------------------------- | ----------------------------------------------------------------------------------------------------- |
| Starting a spinner that's already running       | Check the IsRunning property before calling Start() to prevent unexpected behavior.                   |
| Not unsubscribing from events                   | Always unsubscribe from events to avoid memory leaks, especially in long-running applications.        |
| Blocking the UI thread                          | Ensure that heavy tasks run asynchronously using RunWorkerAsync methods rather than on the UI thread. |
| Ignoring cancellation requests                  | Respect cancellation tokens in background work to ensure tasks can be terminated gracefully.          |
| Improper exception handling in background tasks | Wrap background task code in try-catch blocks and handle OperationCanceledException appropriately.    |

***

### Usage Scenarios

| **Scenario**                        | **Description & Example**                                                                                                              |
| ----------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| Progress Indication                 | Use RunWorkerAsync with progress reporting to indicate task progress via the spinner, updating the UI as needed.                       |
| Visual Feedback During Data Loading | Start the spinner animation while loading data, and stop/reset it once data is loaded.                                                 |
| Batch UI Updates                    | Utilize Configure() to set up the spinner’s appearance and behavior in a single call during application initialization.                |
| Responsive Cancellation             | Implement cancellation logic using the CancellationToken provided in RunWorkerAsync to cancel long-running tasks when the user aborts. |

***

### Review

The General Control Methods & Events feature is central to integrating the SiticoneLoadingSpinner into a .NET WinForms application. By providing intuitive control methods and a robust event-driven model, it enables developers to manage the spinner’s lifecycle effectively and integrate it seamlessly with background processing tasks. The clear separation of start/stop/reset operations and the support for both synchronous and asynchronous background tasks make this control adaptable for various use cases, from simple visual indicators to complex progress-driven interfaces.

***

### Summary

The General Control Methods & Events feature of the SiticoneLoadingSpinner control provides comprehensive management of the spinner’s state through intuitive methods (Start, Stop, Reset, Configure) and detailed event notifications (SpinnerStateChanged, RotationCompleted, ProgressChanged, WorkCompleted). This ensures that developers can easily integrate and control the spinner within their applications while offloading heavy tasks to background processes. Following best practices and avoiding common pitfalls will lead to a smoother, more responsive user experience.

***

### Additional Tips

* **Integration Testing:** When integrating background tasks, ensure that the spinner’s state (running vs. stopped) accurately reflects the background processing status.
* **Resource Management:** Dispose of the spinner control properly to free up resources, especially when using timers and background workers.
* **Customization First:** Leverage the batch configuration capabilities of the Configure() method early in your development process to set a consistent look and behavior for the spinner across your application.

This comprehensive documentation should provide all the necessary details to integrate and use the General Control Methods & Events feature of the SiticoneLoadingSpinner control effectively.
