using Deckungsbeitrag; using Npgsql; using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Management; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace DatenDB { static class DatenbankConnection { private static NpgsqlConnection connection = null; private static readonly int MaxRetries = 3; private static readonly int RetryDelayMs = 1000; // 1 Sekunde public static NpgsqlConnection GetConnection() { if (connection?.State == System.Data.ConnectionState.Open) return connection; connection?.Dispose(); var cs = ConfigurationManager.AppSettings["ConnectionString"]; int attempt = 0; while (true) { try { connection = new NpgsqlConnection(cs); return connection; } catch (NpgsqlException ex) { attempt++; Console.WriteLine($"DB-Connection-Versuch {attempt}"); if (attempt >= MaxRetries) { MessageBox.Show(ex.Message + $"\n\nBitte starte das Programm neu.", "FEHLER", MessageBoxButtons.OK, MessageBoxIcon.Error); Program.AddFehler(null, ex.Message, ex.StackTrace, null); throw; // nach X Versuchen aufgeben } Thread.Sleep(RetryDelayMs); } } } } }