Wait for method to finish an AutoResetEvent without blocking UI

Sorry if this is quite similar to other questions, but I just can't make this work..

How do I run this code, without blocking my ui when calling wh.WaitOne()?

public partial class Form1 : Form
{
    private readonly AutoResetEvent wh = new AutoResetEvent(false);

    public void button1_Click(object sender, EventArgs e)
    {
        //Some work
        MessageBox.Show("Before pause");

        string someVar = activate();

        MessageBox.Show("After pause");
        //some other work which should only run when 'string someVar = activate();' above succeeds
    }

    private string activate()
    {
        wh.WaitOne();
        return textBox1.Text;
    }

    private void button2_Click(object sender, EventArgs e)
    {
        wh.Set();
    }
}

I know I could put the wh.WaitOne() inside a new thread, but return textbox1.Text would get executed right after the thread started without waiting for it to finish. Is there a simple way of waiting for the thread containing wh.WaitOne() to finish perhaps?

Answers


If you use the awaitable AutoResetEvent from Stephen Cleary, you can do it like this:

public partial class Form1 : Form
{
    private readonly AsyncAutoResetEvent wh = new AsyncAutoResetEvent(false);

    public async void button1_Click(object sender, EventArgs e)
    {
        //Some work
        MessageBox.Show("Before pause");

        string someVar = await activate();

        MessageBox.Show("After pause");
        //some other work which should only run when 'string someVar = activate();' above succeeds
    }

    private async Task<string> activate()
    {
        await wh.WaitAsync();
        return textBox1.Text;
    }

    private void button2_Click(object sender, EventArgs e)
    {
        wh.Set();
    }
}

Need Your Help

Fragment - Error inflating

java android xml android-fragments fragment

I am having some problems with my code. I keep getting these errors. I tried searching google and looked at several possible solutions but none of them worked. I have sat with this problem all day ...

Multipeer Connectivity session from Connecting to NotConnected

ios swift macos multipeer-connectivity

I developed a very simple concept project to test Multipeer Connectivity framework on both OS X and iOS platform. They could find each other every time, but cannot be connected. The session state w...