Search code examples
c#eventspuppeteer

Wait for event condition fulfillment


I'm opening a website using Puppeteer and waiting for a certain response in a network panel using the following code:

public string result { get; set; }
IBrowser browser;
private async void button1_Click(object sender, EventArgs e)
{
    await Do();
    await browser.CloseAsync();
    textBox1.AppendText(result);
}

private async Task Do()
{
    var browser = await Puppeteer.LaunchAsync();
    this.browser = browser;
    var page = await browser.NewPageAsync();

    page.Response += async (s, e) =>
    {
        if (e.Response.Request.Url == "URL_1")
        {
            result = await e.Response.TextAsync();

            return;
        }
    };

    await page.GoToAsync("URL_2");
}

On every network response it fires an event checking if response's request url was URL_1 and if so gets response body and writes into textbox, then closes browser. But sometimes it's just closes browser with null in result and nothing in the textbox. I suppose it happens because event's condition wasn't fulfilled and Do() method is just finished.

How can I make it wait for event condition to fulfill and only then finish Do() method?


Solution

  • You can use for example the TaskCompletionSource for signalling

    ...
    var page = await browser.NewPageAsync();
    var tcs = new TaskCompletionSource<object>();
    
    page.Response += async (s, e) =>
    {
        if (e.Response.Request.Url == "URL_1")
        {
            result = await e.Response.TextAsync();
            tcs.SetResult(null); // set the signal
        }
    };
    
    await page.GoToAsync("URL_2");
    await tcs.Task; // wait for the signal