简体   繁体   中英

Program wait for an event to occur in c#

I want this part of my program (I showed in code by "//" sign before the line) to wait until button3 is clicked to resume.

 private void button2_Click(object sender, EventArgs e)
 {
    if (this.textBox3.Text != "")
    {
       this.listView1.Items.Clear();
       //this.listView1.Items.Add(this.textBox3.text);
    }
 }

Seems like you want something like this:

 private void button2_Click(object sender, EventArgs e)
 {
    if (this.textBox3.Text != "")
    {
       this.listView1.Items.Clear();
       button3.Click += Function;
    }
 }
 private void Function(object sender, EventArgs e)
 {
     this.listView1.Items.Add(this.textBox3.text);
     button3.Click -= Function;
 }

So we'll start out with this helper method that produces a task that will be completed when a button is clicked:

public static Task WhenClicked(this Button button)
{
    var tcs = new TaskCompletionSource<bool>();

    EventHandler handler = null;
    handler = (sender , args) =>
    {
        tcs.SetResult(true);
        button.Click -= handler;
    };
    button.Click += handler;

    return tcs.Task;
}

Using this, along with await from C# 5.0, we can create code that reads just like what you requested, even though it produced code similar to what the other answers have (thus maintaining asynchrony and not blocking the UI thread).

private async void button2_Click(object sender, EventArgs e)
{
    if (this.textBox3.Text != "")
    {
        this.listView1.Items.Clear();

        await button3.WhenClicked();

        this.listView1.Items.Add(this.textBox3.text);
    }
}

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