Review generated price notification

from Event subscription and lifetime
C# 14 / .NET 10 advanced 6 min 3 issues to find

Review this generated event code before the feed and dashboard are used in a long-running process.

Notify the dashboard after each price change, finish persistence before Publish returns, allow zero subscribers, and stop notifications when the dashboard is disposed.

csharp
using System; using System.Threading.Tasks;
public sealed record PriceChangedEventArgs(decimal Price) : EventArgs;
public sealed class PriceFeed
{
    public event EventHandler<PriceChangedEventArgs>? PriceChanged;
    public void Publish(decimal price) =>
        PriceChanged!.Invoke(this, new PriceChangedEventArgs(price));
}
public sealed class Dashboard : IDisposable
{
    private readonly PriceFeed _feed;
    public Dashboard(PriceFeed feed)
    {
        _feed = feed;
        _feed.PriceChanged += async (_, e) =>
        {
            await SaveAsync(e.Price);
            Console.WriteLine($"saved: {e.Price}");
        };
    }
    public void Dispose() =>
        _feed.PriceChanged -= async (_, e) => await SaveAsync(e.Price);
    private async Task SaveAsync(decimal price) =>
        await Task.Delay(10);
}

generated code is illustrative, not from any one model

Open in playground
Report an error