等待方法完成AutoResetEvent而不阻止UI

时间:2016-01-17 17:12:35

标签: c# multithreading winforms

很抱歉,如果这与其他问题非常相似,但我无法做到这一点..

如何在调用wh.WaitOne()时阻止我的ui运行此代码?

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

我知道我可以将wh.WaitOne()放在一个新线程中,但return textbox1.Text会在线程启动后立即执行而不等待它完成。是否有一种简单的方法可以等待包含wh.WaitOne()的线程完成?

1 个答案:

答案 0 :(得分:1)

如果你使用awaitable AutoResetEvent from Stephen Cleary,你可以这样做:

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