简体   繁体   中英

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?

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();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM