TechnitiumSoftware/DnsServer · error · InvalidOperationException

DHCP Server is already running.

Error message

DHCP Server is already running.

What it means

Start() refuses to run because the service is not in the Stopped state (it is Starting/Running/Stopping). This is an InvalidOperationException, not a DhcpServerException, signalling a lifecycle misuse.

Source

Thrown at DnsServerCore/Dhcp/DhcpServer.cs:1398

            _maintenanceTimer.Change(MAINTENANCE_TIMER_INTERVAL, Timeout.Infinite);
        }

        private void StopMaintenanceTimer()
        {
            _maintenanceTimer.Change(Timeout.Infinite, Timeout.Infinite);
        }

        #endregion

        #region public

        public void Start()
        {
            if (_disposed)
                ObjectDisposedException.ThrowIf(_disposed, this);

            if (_state != ServiceState.Stopped)
                throw new InvalidOperationException("DHCP Server is already running.");

            _state = ServiceState.Starting;

            LoadAllScopeFiles();
            StartMaintenanceTimer();

            _state = ServiceState.Running;
        }

        public void Stop()
        {
            if (_state != ServiceState.Running)
                return;

            _state = ServiceState.Stopping;

            StopMaintenanceTimer();

View on GitHub (pinned to d0484b6c1e)

Solutions

  1. Call Stop() and wait until state == Stopped before calling Start().
  2. Guard the caller: only Start() when _state == Stopped.
  3. Audit for concurrent/re-entrant Start() invocations.

Example fix

// before
if (_dhcpServer.State != ServiceState.Running) _dhcpServer.Start(); // can throw if Starting
// after
_dhcpServer.Stop();
while (_dhcpServer.State != ServiceState.Stopped) Thread.Yield();
_dhcpServer.Start();
Defensive patterns

Strategy: validation

Validate before calling

if (_dhcpServer.State != ServiceState.Stopped)
    throw new InvalidOperationException("DHCP server must be stopped before Start()");

Type guard

static bool CanStart(DhcpServer s) => s.State == ServiceState.Stopped;

Try / catch

try { _dhcpServer.Start(); }
catch (InvalidOperationException ex) when (ex.Message.Contains("already running"))
{ /* already started; no-op or Stop()+Start() */ }

Prevention

When it happens

Trigger: Calling DhcpServer.Start() when _state != ServiceState.Stopped (e.g. already Running, or mid-Start).

Common situations: Double Start() call. Service controller restart that calls Start before Stop completed. UI button that starts while starting.

Related errors


AI-assisted analysis of TechnitiumSoftware/DnsServer@d0484b6c1e (2026-08-13). Data as JSON: /api/errors/3d318482f8c367e7. Report an issue: GitHub.