Surprisingly a stack overflow exception can be caused by repeatedly calling Window.ShowDialog asynchronously.
public MainWindow()
{
InitializeComponent();
TheCallDelegate = TheCall;
_timer = new DispatcherTimer();
_timer.Tick += _timer_Tick;
_timer.Start();
}
DispatcherTimer _timer = null;
void _timer_Tick(object sender, EventArgs e)
{
_timer.Dispatcher.BeginInvoke(TheCallDelegate);
}
Action TheCallDelegate;
void TheCall()
{
Window win = new Window();
win.ShowDialog();
}
As you can see there is no actual recursion here (or there shouldn't have been) but once the exception happens you can see that the call stack is indeed full. Why? This can also be achieved without the use of a timer like so:
private async void Button_Click(object sender, RoutedEventArgs e)
{
while (true)
{
this.Dispatcher.BeginInvoke(TheCallDelegate);
await Task.Delay(1);
}
}
P.S. The code you see here is constructed specifically to illustrate the question so don't focus on why would anyone do this. The purpose of the question is to understand why does ShowDialog behave in this way.