I have an async void event handler that creates and a Form and passes it a SempahoreSlim with initial count 0 and then waits asyncronously on it (showing the form before wait). When I click a button in the Form the semaphore is released and the event handler continues execution on same context (UIThread). Debugging I found that sometimes when the Form is shown and DefWndProc is called (called internally by the .Net Framework Form class implementation) the application freezes. Why?
class DebugForm : Form
{
SemaphoreSlim waitOK;
public DebugForm (SemaphoreSlim waitOK)
{
InitializeComponent();
this.waitOK = waitOK;
}
//Added in InitializeComponent
async void buttonOK_Click(object sender, EventArgs e)
{
//Do stuff with UI
waitOK.Release();
}
}
In My MainForm load event I do this:
async void MainForm_Load(object sender, EventArgs e)
{
SemaphoreSlim sem = new SemaphoreSlim(0);
Form debugForm = new DebugForm(sem);
//It stucks in the Show call sometimes with low probability
debugForm.Show();
await sem.WaitAsync();
//Do other Stuff
}