# Best Practices: Reliable Auto-Save in TX Text Control Using the WebSocketHandler and Background Services

> When developing modern document processing applications with TX Text Control, data loss prevention is a critical requirement. This article explores the best practices for implementing a reliable autosave feature using WebSocketHandler and Background Services in ASP.NET Core.

- **Author:** Bjoern Meyer
- **Published:** 2025-06-20
- **Modified:** 2025-11-16
- **Description:** When developing modern document processing applications with TX Text Control, data loss prevention is a critical requirement. This article explores the best practices for implementing a reliable autosave feature using WebSocketHandler and Background Services in ASP.NET Core.
- **4 min read** (689 words)
- **Tags:**
  - ASP.NET
  - ASP.NET Core
- **Web URL:** https://www.textcontrol.com/blog/2025/06/20/best-practices-reliable-auto-save-in-tx-text-control-using-the-websockethandler-and-background-services/
- **LLMs URL:** https://www.textcontrol.com/blog/2025/06/20/best-practices-reliable-auto-save-in-tx-text-control-using-the-websockethandler-and-background-services/llms.txt
- **LLMs-Full URL:** https://www.textcontrol.com/blog/2025/06/20/best-practices-reliable-auto-save-in-tx-text-control-using-the-websockethandler-and-background-services/llms-full.txt
- **GitHub Repository:** https://github.com/TextControl/TXTextControl.Web.Core.Reconnect

---

When developing modern document processing applications with TX Text Control, data loss prevention is a critical requirement. A common scenario involves a temporary client-side network outage interrupting the WebSocket connection between the document editor and the server. If the document is only stored locally, this could result in data loss.

To address this challenge, we implemented a server-side autosave strategy that saves documents independently of the stability of the WebSocket connection. This is a best practice for mission-critical environments, such as healthcare and legal applications.

This article walks through the code of a reference implementation that uses a background service and the *WebSocketHandler* to continuously save document data on the server.

####  Why Auto-Save Server-Side?

TX Text Control provides access to the loaded document via the *WebSocketHandler* on the server. Periodically saving the document via this handler avoids:

- Interfering with the active WebSocket communication to the client
- Data loss when the WebSocket connection drops (e.g., due to an internet issue on the client side)

The document is stored in memory in an internal format and can be saved to a database, disk, or blob storage later.

### Key Components of the Strategy

The implementation consists of the following key components:

- **DocumentStore**: In-Memory Document Buffer
- **AutoSaveService**: Background Document Saver
- **AutoSaveController**: Document Session Management

#### DocumentStore

This static store maps a connection ID, which is associated with a client, to the current document in byte format. It is thread-safe and lightweight, making it ideal for temporarily caching document data.

```
public static class DocumentStore
{
    public static readonly ConcurrentDictionary<string, byte[]> Documents = new();

    public static void RegisterConnection(string connectionId) => 
        Documents.TryAdd(connectionId, Array.Empty<byte>());

    public static void UpdateDocument(string connectionId, byte[] newContent) => 
        Documents[connectionId] = newContent ?? Array.Empty<byte>();

    public static bool Remove(string connectionId) => 
        Documents.TryRemove(connectionId, out _);

    public static IEnumerable<KeyValuePair<string, byte[]>> GetAll() => 
        Documents.ToArray();
}
```

#### AutoSaveService

This service calls *SaveText* on each active *WebSocketHandler* every 5 seconds and updates the document in memory. Since these calls are made asynchronously and independently of the UI thread, they have no impact on the user's editing experience. The interval is hardcoded, but you're welcome to put this into an application config file and tweak this number as needed.

```
public class AutoSaveService : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            await Task.Delay(_interval, stoppingToken);

            foreach (var kvp in DocumentStore.Documents)
            {
                SaveDocument(kvp.Key);
            }
        }
    }

    private void SaveDocument(string connectionId)
    {
        var handler = WebSocketHandler.GetInstance(connectionId);
        if (handler == null) return;

        handler.SaveText(out var data, BinaryStreamType.InternalUnicodeFormat);
        DocumentStore.UpdateDocument(connectionId, data);
    }
}
```

#### AutoSaveController

The controller provides endpoints for registering, unregistering, and querying document sessions. This allows clients to explicitly start or stop tracking a document's lifecycle.

```
[ApiController]
[Route("[controller]")]
public class AutoSaveController : ControllerBase
{
    [HttpPost("RegisterConnection")]
    public IActionResult RegisterConnection([FromQuery] string connectionId)
    {
        DocumentStore.RegisterConnection(connectionId);
        return Ok();
    }

    [HttpDelete("UnregisterConnection")]
    public IActionResult UnregisterConnection([FromQuery] string connectionId)
    {
        return DocumentStore.Remove(connectionId) ? Ok() : NotFound();
    }

    [HttpGet("GetDocument")]
    public IActionResult GetDocument([FromQuery] string connectionId)
    {
        if (!DocumentStore.Documents.TryGetValue(connectionId, out var doc))
            return NotFound();

        return Ok(doc);
    }
}
```

#### Resilience in Unstable Networks

In the event of a network outage, the WebSocket connection may drop, but the *AutoSaveService* continues to run in the background. This ensures that the document remains up-to-date on the server, even if the client cannot receive updates. Once the connection is restored, the client can retrieve the latest version of the document from the server.

The advantage of the TX Text Control editor is that the document lives on the server. Even if the internet connection is lost, the document can be securely saved. It is important to have a data loss strategy when handling sensitive data.

- The last known state is saved server-side in memory.
- Recovery logic can rehydrate the session or prompt the user to reload the last auto-saved version.

This provides a reliable backup option for scenarios with poor connectivity.

### Conclusion

Implementing a server-side auto-save strategy with TX Text Control enhances data integrity and user experience in document processing applications. By leveraging the *WebSocketHandler* and a background service, developers can ensure that documents are continuously saved, minimizing the risk of data loss during network interruptions.

You can download the complete code for this implementation from our GitHub repository.

---

## About Bjoern Meyer

As CEO, Bjoern is the visionary behind our strategic direction and business development, bridging the gap between our customers and engineering teams. His deep passion for coding and web technologies drives the creation of innovative products. If you're at a tech conference, be sure to stop by our booth - you'll most likely meet Bjoern in person. With an advanced graduate degree (Dipl. Inf.) in Computer Science, specializing in AI, from the University of Bremen, Bjoern brings significant expertise to his role. In his spare time, Bjoern enjoys running, paragliding, mountain biking, and playing the piano.

- [LinkedIn](https://www.linkedin.com/in/bjoernmeyer/)
- [X](https://x.com/txbjoern)
- [GitHub](https://github.com/bjoerntx)

---

## Related Posts

- [Major SignFabric Updates: Stronger Audit Trails, Validation, and Recipient Workflows](https://www.textcontrol.com/blog/2026/06/17/major-signfabric-updates-stronger-audit-trails-validation-and-recipient-workflows/llms.txt)
- [Text Control Expands North American Conference Presence with WeAreDevelopers World Congress North America](https://www.textcontrol.com/blog/2026/06/12/text-control-expands-north-american-conference-presence-with-wearedevelopers-world-congress-north-america/llms.txt)
- [Converting HTML to Markdown in C# .NET](https://www.textcontrol.com/blog/2026/06/11/converting-html-to-markdown-in-csharp-dot-net/llms.txt)
- [Beyond WebSockets: A Glimpse into the Future of Document Editing with WebAssembly](https://www.textcontrol.com/blog/2026/06/10/beyond-websockets-glimpse-future-document-editing-webassembly/llms.txt)
- [Showcasing the Future of Document Processing at Developer World DWX 2026](https://www.textcontrol.com/blog/2026/06/08/showcasing-the-future-of-document-processing-at-dwx-developer-week-2026/llms.txt)
- [PDF Security Explained: Passwords, Permissions, Encryption and Digital Signatures in C# .NET](https://www.textcontrol.com/blog/2026/06/08/pdf-security-explained-passwords-permissions-encryption-and-digital-signatures-in-csharp-dotnet/llms.txt)
- [NDC Copenhagen 2026: Great Days in the Heart of Copenhagen's Developer Community](https://www.textcontrol.com/blog/2026/06/05/ndc-copenhagen-2026-great-days-in-the-heart-of-copenhagens-developer-community/llms.txt)
- [Automatically Mapping TX Text Control Form Fields to JSON Data in .NET C#](https://www.textcontrol.com/blog/2026/06/03/automatically-mapping-tx-text-control-form-fields-to-json-data-in-dotnet-csharp/llms.txt)
- [Getting Started with SignFabric: From Clone to Your First Signature Envelope](https://www.textcontrol.com/blog/2026/06/02/getting-started-with-signfabric-from-clone-to-your-first-signature-envelope/llms.txt)
- [We Never Pause - Join Us at NDC Copenhagen 2026](https://www.textcontrol.com/blog/2026/05/27/we-never-pause-join-us-at-ndc-copenhagen-2026/llms.txt)
- [MD DevDays 2026: Record Attendance, Packed Expo Hall, and Three Great Days in Magdeburg](https://www.textcontrol.com/blog/2026/05/21/md-devdays-2026-record-attendance-packed-expo-hall-and-three-great-days-in-magdeburg/llms.txt)
- [TX Text Control 34.0 SP4 is Now Available: What's New in the Latest Version](https://www.textcontrol.com/blog/2026/05/20/tx-text-control-34-0-sp4-is-now-available/llms.txt)
- [Techorama 2026: Welcome to The Document Forge](https://www.textcontrol.com/blog/2026/05/15/techorama-2026-welcome-to-the-document-forge/llms.txt)
- [Signed CycloneDX SBOMs for CRA Compliance Available for Text Control Products](https://www.textcontrol.com/blog/2026/05/08/signed-cyclonedx-sboms-for-cra-compliance-available-for-text-control-products/llms.txt)
- [Introducing SignFabric: An Open Source, Enterprise-Ready E-Sign Platform Built with TX Text Control](https://www.textcontrol.com/blog/2026/05/06/introducing-signfabric-an-open-source-enterprise-ready-esign-platform-built-with-tx-text-control/llms.txt)
- [TX Text Control vs IronPDF for Enterprise PDF Workflows: Complete Comparison Guide](https://www.textcontrol.com/blog/2026/04/28/tx-text-control-vs-ironpdf-for-enterprise-pdf-workflows-complete-comparison-guide/llms.txt)
- [Building a Modern Track Changes Review Workflow in ASP.NET Core C#](https://www.textcontrol.com/blog/2026/04/28/building-a-modern-track-changes-review-workflow-in-aspnet-core-csharp/llms.txt)
- [Document Classification Without AI: Deterministic, Explainable, and Built for Production in C# .NET](https://www.textcontrol.com/blog/2026/04/23/document-classification-without-ai-deterministic-explainable-built-for-production-in-csharp-dot-net/llms.txt)
- [Using QR Codes in PDF Documents in C# .NET](https://www.textcontrol.com/blog/2026/04/21/using-qr-codes-in-pdf-documents-in-csharp-dotnet/llms.txt)
- [Sanitizing Data in Document Pipelines: A Practical Approach with TX Text Control in C# .NET](https://www.textcontrol.com/blog/2026/04/20/sanitizing-data-in-document-pipelines-a-practical-approach-with-tx-text-control-in-csharp-dotnet/llms.txt)
- [One More Stop on Our Conference Circus: code.talks 2026](https://www.textcontrol.com/blog/2026/04/17/one-more-stop-on-our-conference-circus-code-talks-2026/llms.txt)
- [Build Your Own MCP-Powered Document Processing Backend with TX Text Control](https://www.textcontrol.com/blog/2026/04/16/build-your-own-mcp-powered-document-processing-backend-with-tx-text-control/llms.txt)
- [TXTextControl.Markdown.Core 34.1.0-beta: Work with Full Documents, Selection, and SubTextParts](https://www.textcontrol.com/blog/2026/04/14/txtextcontrol-markdown-core-34-1-0-beta-work-with-full-documents-selection-and-subtextparts/llms.txt)
- [5 Layout Patterns for Integrating the TX Text Control Document Editor in ASP.NET Core C#](https://www.textcontrol.com/blog/2026/04/09/5-layout-patterns-for-integrating-the-tx-text-control-document-editor-in-aspnet-core-csharp/llms.txt)
- [Extracting Structured Table Data from DOCX Word Documents in C# .NET with Domain-Aware Table Detection](https://www.textcontrol.com/blog/2026/04/03/extracting-structured-table-data-from-docx-word-documents-in-csharp-dotnet-with-domain-aware-table-detection/llms.txt)
