Hi GOLF,
The synchronization failure you are seeing stems from the way the Windows.Media.Casting stack handles state transitions within the underlying Wi-Fi Direct and RTSP layers. When a programmatic reconnection is triggered too rapidly, the CastingConnection object often fails to transition fully to a terminal Disconnected state, leaving the State property stuck in an intermediate phase that the UI incorrectly interprets as an active or pending connection. This is typically caused by residual handles in the media projection engine that do not clear until the original object is completely destroyed and the transport layer acknowledges the tear-down.
To fix this for your demo environment, you must implement a strict "dispose and recreate" pattern rather than attempting to recycle the existing connection. Before initiating a reconnection, you need to call DisconnectAsync and immediately unregister all StateChanged and ErrorOccurred event handlers to prevent them from firing against a stale object. Once the handlers are removed, set your CastingConnection instance to null. You should then wait for a brief period—ideally through a task delay—to allow the system to release the network resources before calling CreateCastingConnection on your CastingDevice again to obtain a fresh, clean instance.
For maximum reliability, implement a watchdog timer that monitors the connection progress. If the state remains stuck at Connecting for more than ten seconds, you should programmatically force a reset of the device watcher. This ensures that the application forces the Windows shell to rediscover the Miracast receiver, which effectively flushes the faulty state synchronization and restores the correct status to your application's interface.
Hope this answer brought you some useful information. If it did, please hit “accept answer”. Should you have any questions, feel free to leave a comment.
VP