In this paper, we propose an innovative approach for the real-time optimal control of district heating networks during anomalous conditions. We aim at minimizing the maximum thermal discomfort of the connected users after a pipe breakage by an integrated and centralized management of the user controlvalves. Our control strategy uses a gradient-based optimizer driven by discrete adjoint sensitivities, which makes it fast and nearly insensitive to the problem dimensions. We tested the proposed approach by simulating a set of different malfunctions in the Turin District heating network and by analyzing the building temperature field during the optimizer convergence history. Compared to the control strategy in use today, we observe that our approach flattens the temperature field and eliminates discomfort peaks, bringing a considerable increase of the minimum user temperature which ranges from a minimum of 1.8 °C to a maximum of 15.4 °C. Furthermore, our optimization strategy allows for superior results to what is achievable conventionally with an 85 % increase of the pumping head, making back-up pumping devices a non-necessary investment.