playwright-dotnet: [Bug]: after about 833 times different context running with same browser, browser close automatically

Playwright version

1.12.2

Operating system

Windows

What browsers are you seeing the problem on?

WebKit

Other information

.NET 5.0.301

What happened? / Describe the bug

I use playwright in a background service in .NET 5 console project. I use DI to run playwright to browser some websites and wait for response, get some attributes, like _browserContext.NewPageAsync(), page.GotoAsync, page.WaitForResponseAsync, page.GetAttributeAsync, response.TextAsync() and something like these methods. But every time when run to about No.833+ contexts (I will dispose one after one every time) public async void Dispose() { await _browserContext.CloseAsync(); await _browserContext.DisposeAsync(); GC.SuppressFinalize(this); } with one browser but different context, about 833times later, browser will automatically down. Logs below. Is there anything I did wrong? Thanks developer and community! Forgive my bad English.

Code snippet to reproduce your bug

services.TryAddSingleton<IPlaywright>(Playwright.CreateAsync().Result);
            services.TryAddSingleton<IBrowser>(provider =>
            {
                var playwright = provider.GetService<IPlaywright>();
                if (playwright != null)
                    return playwright.Webkit.LaunchAsync().Result;
                throw new Exception("Fail");
            });
            services.TryAdd(new ServiceDescriptor(typeof(IBrowserContext), provider =>
            {
                var browser = provider.GetService<IBrowser>();
                var context = browser!.NewContextAsync(new BrowserNewContextOptions()
                {
                    UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
                    ExtraHTTPHeaders = new List<KeyValuePair<string, string>>()
                    {
                        new ("Accept-Language","en-US,en;q=0.9")
                    }
                }).Result;
                context.SetDefaultNavigationTimeout(6_000);
                context.SetDefaultTimeout(6_000);
                return context;
            }, contextLifetime));

Relevant log output

`Microsoft.Playwright.PlaywrightException: Protocol error (Dialog.enable): Browser closed.
==================== Browser output: ====================
<launching> C:\Users\Administrator\AppData\Local\ms-playwright\webkit-1492\Playwright.exe --inspector-pipe --headless --no-startup-window
<launched> pid=15044
[pid=15044][err] 1   00007FFF46981089
[pid=15044][err] 2   00007FFF469F7C59
[pid=15044][err] 3   00007FFF469A4B75
[pid=15044][err] 4   00007FFF469F497E
[pid=15044][err] 5   00007FFF469A863F
[pid=15044][err] 6   00007FFF469F8F59
[pid=15044][err] 7   00007FFF698D268A
[pid=15044][err] 8   00007FFF6C6F7974
[pid=15044][err] 9   00007FFF6D06A2F1
[pid=15044] <process did exit: exitCode=3221225477, signal=null>
[pid=15044] starting temporary directories cleanup
[pid=15044] finished temporary directories cleanup
   at Microsoft.Playwright.Transport.Connection.SendMessageToServerAsync[T](String guid, String method, Object args)
   at Microsoft.Playwright.BrowserContext.NewPageAsync()`

About this issue

  • Original URL
  • State: closed
  • Created 5 years ago
  • Comments: 15 (6 by maintainers)

Most upvoted comments

please help me review this issue. @kblok @avodovnik @Meir017 @pavelfeldman @SimonCropp @slang25 @ScottHuangZL @aslushnikov thank you my teachers

And the example I used was single-threaded and did not involve parallel or multi-threaded at all

This is intended and not a bug. You need to limit the maximum parallel contexts. I’m not familiar with .NET, but this looks like what you want: https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.paralleloptions.maxdegreeofparallelism?redirectedfrom=MSDN&view=net-5.0#System_Threading_Tasks_ParallelOptions_MaxDegreeOfParallelism

In other languages its called a worker group with a maximum concurrency limit.

TL;DR: Relates microsoft/playwright#6319 and a massive amount of contexts is not supported.

I don’t think so. It doesn’t make any sense. @avodovnik 's example also used

await using var context = await browser.NewContextAsync();

so I don’t think it relates to limiting the maximum parallel contexts…

just

public static void AddMyService(this IServiceCollection services, ServiceLifetime contextLifetime = ServiceLifetime.Scoped)
{
	services.TryAddSingleton<IPlaywright>(Playwright.CreateAsync().Result);
	services.TryAddSingleton<IBrowser>(provider =>
	{
		var playwright = provider.GetService<IPlaywright>();
		if (playwright != null)
			return playwright.Webkit.LaunchAsync().Result;
		throw new Exception("Fail 1");
	});
	services.TryAdd(new ServiceDescriptor(typeof(IBrowserContext), provider =>
	{
		var browser = provider.GetService<IBrowser>();
		var context = browser!.NewContextAsync(new BrowserNewContextOptions()
		{
			UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
			ExtraHTTPHeaders = new List<KeyValuePair<string, string>>()
			{
						new ("Accept-Language","en-US,en;q=0.9")
			}
		}).Result;
		context.SetDefaultNavigationTimeout(6_000);
		context.SetDefaultTimeout(6_000);
		return context;
	}, contextLifetime));
	services.TryAdd(new ServiceDescriptor(typeof(MyService), typeof(MyService), contextLifetime));
}

and in my background service project contextLifetime is services.AddMyService(contextLifetime: ServiceLifetime.Transient);

in background service project: code below the query object is a list<T>, it’s count about 1000+, and every time the foreach loop get about 833+, Playwright.exe crash🤦‍♂️

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
	foreach (var item in query)
	{
		using var myService = _provider.GetService<MyService>();
                var id = item.Id;//xxxxxx
		await mySevice.BrowserAll();
	}
}

and in my service code (pseudocode)

public class MyService : IDisposable
{
	private readonly ILogger<MyService> _logger;
	private readonly IBrowserContext _browserContext;

	public MyService(IBrowserContext browserContext, ILogger<MyService> logger)
	{
		_logger = logger;
		_browserContext = browserContext;
	}

	public async Task BrowserAll()
	{
		var page = await _browserContext.NewPageAsync();
		await page.GotoAsync("www.xxx.com");
		var response = await page.WaitForResponseAsync(res => res.Url == "www.xxx.com/ok" && res.Status == 200, new PageWaitForResponseOptions()
		{
			Timeout = 5_000,
		});
		await page.RouteAsync(pseudocode);
	}

	public async void Dispose()
	{
		await _browserContext.CloseAsync();
		await _browserContext.DisposeAsync();
		GC.SuppressFinalize(this);
	}

}