Introduction to Data Management with Expiration

Welcome to the first step in building our C#-based backend system. In this unit, we will focus on how to manage user data with expiration. This is a fundamental part of our project that will set the stage for more advanced features in later units.

Setting Up a Simple Data Store with Expiration in C#

Let's explore how to manage user data with expiration in a C# environment. We will cover the basic operations for managing user data:

  1. Adding user data with an expiration time: This will ensure that user data is stored for a limited period and automatically deleted afterward.
  2. Retrieving user data: This operation will help us fetch the user data we previously stored.

For demonstration purposes, we will use a simple in-memory storage mechanism along with System.Threading timers to simulate expiration functionality.

Here's a quick example of how we can structure these operations in C#:

C#
using System;
using System.Collections.Generic;
using System.Threading;

class Program
{
    static Dictionary<string, Tuple<string, Timer>> dataStore = new Dictionary<string, Tuple<string, Timer>>();

    static void Main()
    {
        AddUserDataWithExpiration("user1", "{ 'email': 'user1@example.com' }", TimeSpan.FromDays(1));
        
        string data = RetrieveUserData("user1");
        Console.WriteLine(data); // Output: { 'email': 'user1@example.com' }
    }

    static void AddUserDataWithExpiration(string key, string data, TimeSpan expiration)
    {
        Timer timer = new Timer(RemoveUserData, key, expiration, Timeout.InfiniteTimeSpan);
        dataStore[key] = new Tuple<string, Timer>(data, timer);
    }
    
    static string RetrieveUserData(string key)
    {
        if (dataStore.ContainsKey(key))
        {
            return dataStore[key].Item1;
        }
        return null;
    }

    static void RemoveUserData(object state)
    {
        string key = (string)state;
        if (dataStore.ContainsKey(key))
        {
            dataStore[key].Item2.Dispose();
            dataStore.Remove(key);
        }
    }
}

In this example, we are using a Dictionary to store user data and a Timer to handle the expiration. When the timer elapses, the corresponding user data is automatically removed from storage.

Note: While using a dictionary and timer for expiration works in a simple in-memory setup, it has several drawbacks:

  • The data is lost if the application restarts since it is stored in memory.
  • Timers remain active as long as the application runs, which can cause memory leaks if not handled properly.
  • Scaling this solution across multiple instances of an application is not feasible.
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal