簡體   English   中英

等待方法完成AutoResetEvent而不會阻塞UI

[英]Wait for method to finish an AutoResetEvent without blocking UI

抱歉,如果這與其他問題十分相似,但我無法完成這項工作。

如何在調用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將在線程啟動后return textbox1.Text執行,而無需等待其完成。 是否有一種簡單的方法來等待包含wh.WaitOne()的線程完成?

如果您使用來自Stephen Clearyawaitable AutoResetEvent ,則可以這樣進行:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM