0

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
}
Federico
  • 1
  • 1
  • You may need to pump the event loop, try this answer https://stackoverflow.com/a/1918955/920557 by adding the `Application.DoEvents();` right after your call to `Show()`. – Eugene Komisarenko Jul 27 '17 at 23:48
  • 2
    @EugeneKomisarenko: there is never any reason to call `DoEvents()` in a well-written Winforms program. But beyond that, since the comment in the code says that it's the `Show()` method itself that hangs, it seems completely unlikely that adding code _after_ that call would help anything. – Peter Duniho Jul 28 '17 at 00:25
  • I understand that `Application.DoEvents();` creates a new message loop, that seems a bit of overhead. It can also lead to deadlocks. The only secure way I know to use it is disabling the main Form while this method is called see Hans Passant answer to [this](https://stackoverflow.com/questions/5181777/use-of-application-doevents) post. – Federico Jul 28 '17 at 18:47

0 Answers0