将任务添加到任何异步
我希望收听任务的结果,或者如果没有制作或完成,则暂停。具体来说,我正在使用剧作家,并正在为请求添加一个事件侦听器,并且如果这些请求都不包括我要寻找的内容(甚至创建),则希望超时。下面的示例代码:
我已经尝试调查何时何时,但这需要提前了解任务。还研究了Monitor.tryenter,但不确定如何在生成锁之前获得请求?也许是信号量之类的?
string? result = null;
// Start listening for new pages (ClickAsync below opens in a new page)
context.Page += (_, newPage) =>
{
// From the new page, start listening for requests that page generates
newPage.Request += async (_, request) =>
{
if (request.Url.Contains("some_identifier"))
{
await newPage.GotoAsync(request.Url);
result = await newPage.InnerTextAsync("body");
// Do something here? We now have the result we want, stop waiting and return it!
}
};
};
await mainPage.Locator("a#somelink").ClickAsync();
// Wait for *up to* 30 seconds here.
return result;
I'm looking to listen to the result of a task(s), or timeout if the none are made or completed. Specifically, I'm using Playwright and am adding an event listener for requests and want to timeout if none of those requests include what I'm looking for (or even get created). Example code below:
I've tried looking into WhenAny, but that requires knowing the tasks ahead of time. Also looked into Monitor.TryEnter, but not sure how to have the requests acquire the lock before they're generated? Maybe a semaphore or something?
string? result = null;
// Start listening for new pages (ClickAsync below opens in a new page)
context.Page += (_, newPage) =>
{
// From the new page, start listening for requests that page generates
newPage.Request += async (_, request) =>
{
if (request.Url.Contains("some_identifier"))
{
await newPage.GotoAsync(request.Url);
result = await newPage.InnerTextAsync("body");
// Do something here? We now have the result we want, stop waiting and return it!
}
};
};
await mainPage.Locator("a#somelink").ClickAsync();
// Wait for *up to* 30 seconds here.
return result;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
利用我的回答评论中的想法,我能够实现目标。我最终将取消令牌传递给了一个任务。delay(30000,令牌)。然后,如果我获得了想要的数据并设置结果值,我只是取消了令牌。
Using ideas from comments on my answer I was able to accomplish the goal. I ended up passing a cancellation token to a Task.Delay(30000, token). Then if I got the data I wanted and set the result value, I just cancelled the token.