How to use StartAsync method of PuppeteerSharp.States.ChromiumStartingState class

Best Puppeteer-sharp code snippet using PuppeteerSharp.States.ChromiumStartingState.StartAsync

Run Puppeteer-sharp automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

ChromiumStartingState.cs

Source: ChromiumStartingState.cs Github

copy
1using System;
2using System.Diagnostics;
3using System.Text;
4using System.Text.RegularExpressions;
5using System.Threading;
6using System.Threading.Tasks;
7
8namespace PuppeteerSharp.States
9{
10    internal class ChromiumStartingState : State
11    {
12        public ChromiumStartingState(StateManager stateManager) : base(stateManager)
13        {
14        }
15
16        public override Task EnterFromAsync(LauncherBase p, State fromState, TimeSpan timeout)
17        {
18            if (!StateManager.TryEnter(p, fromState, this))
19            {
20                // Delegate StartAsync to current state, because it has already changed since
21                // transition to this state was initiated.
22                return StateManager.CurrentState.StartAsync(p);
23            }
24
25            return StartCoreAsync(p);
26        }
27
28        public override Task StartAsync(LauncherBase p) => p.StartCompletionSource.Task;
29
30        public override Task ExitAsync(LauncherBase p, TimeSpan timeout) => StateManager.Exiting.EnterFromAsync(p, this, timeout);
31
32        public override Task KillAsync(LauncherBase p) => StateManager.Killing.EnterFromAsync(p, this);
33
34        public override void Dispose(LauncherBase p)
35        {
36            p.StartCompletionSource.TrySetException(new ObjectDisposedException(p.ToString()));
37            base.Dispose(p);
38        }
39
40        protected virtual async Task StartCoreAsync(LauncherBase p)
41        {
42            var output = new StringBuilder();
43
44            void OnProcessDataReceivedWhileStarting(object sender, DataReceivedEventArgs e)
45            {
46                if (e.Data != null)
47                {
48                    output.AppendLine(e.Data);
49                    var match = Regex.Match(e.Data, "^DevTools listening on (ws:\\/\\/.*)");
50                    if (match.Success)
51                    {
52                        p.StartCompletionSource.TrySetResult(match.Groups[1].Value);
53                    }
54                }
55            }
56
57            void OnProcessExitedWhileStarting(object sender, EventArgs e)
58                => p.StartCompletionSource.TrySetException(new ProcessException($"Failed to launch browser! {output}"));
59
60            void OnProcessExited(object sender, EventArgs e) => StateManager.Exited.EnterFrom(p, StateManager.CurrentState);
61
62            p.Process.ErrorDataReceived += OnProcessDataReceivedWhileStarting;
63            p.Process.Exited += OnProcessExitedWhileStarting;
64            p.Process.Exited += OnProcessExited;
65            CancellationTokenSource cts = null;
66            try
67            {
68                p.Process.Start();
69                await StateManager.Started.EnterFromAsync(p, this).ConfigureAwait(false);
70
71                p.Process.BeginErrorReadLine();
72
73                var timeout = p.Options.Timeout;
74                if (timeout > 0)
75                {
76                    cts = new CancellationTokenSource(timeout);
77                    cts.Token.Register(() => p.StartCompletionSource.TrySetException(
78                        new ProcessException($"Timed out after {timeout} ms while trying to connect to Base!")));
79                }
80
81                try
82                {
83                    await p.StartCompletionSource.Task.ConfigureAwait(false);
84                    await StateManager.Started.EnterFromAsync(p, this).ConfigureAwait(false);
85                }
86                catch
87                {
88                    await StateManager.Killing.EnterFromAsync(p, this).ConfigureAwait(false);
89                    throw;
90                }
91            }
92            finally
93            {
94                cts?.Dispose();
95                p.Process.Exited -= OnProcessExitedWhileStarting;
96                p.Process.ErrorDataReceived -= OnProcessDataReceivedWhileStarting;
97            }
98        }
99    }
100}
101
Full Screen

LauncherBase.cs

Source: LauncherBase.cs Github

copy
1using System;
2using System.Collections;
3using System.Collections.Generic;
4using System.Diagnostics;
5using System.Linq;
6using System.Text;
7using System.Text.RegularExpressions;
8using System.Threading;
9using System.Threading.Tasks;
10using Microsoft.Extensions.Logging;
11using PuppeteerSharp.Helpers;
12using PuppeteerSharp.States;
13
14namespace PuppeteerSharp
15{
16    /// <summary>
17    /// Represents a Base process and any associated temporary user data directory that have created
18    /// by Puppeteer and therefore must be cleaned up when no longer needed.
19    /// </summary>
20    public class LauncherBase : IDisposable
21    {
22        private readonly StateManager _stateManager;
23
24        /// <summary>
25        /// Creates a new <see cref="LauncherBase"/> instance.
26        /// </summary>
27        /// <param name="executable">Full path of executable.</param>
28        /// <param name="options">Options for launching Base.</param>
29        public LauncherBase(string executable, LaunchOptions options)
30        {
31            _stateManager = new StateManager();
32            _stateManager.Starting = new ChromiumStartingState(_stateManager);
33
34            Options = options ?? throw new ArgumentNullException(nameof(options));
35
36            Process = new Process
37            {
38                EnableRaisingEvents = true
39            };
40            Process.StartInfo.UseShellExecute = false;
41            Process.StartInfo.FileName = executable;
42            Process.StartInfo.RedirectStandardError = true;
43
44            SetEnvVariables(Process.StartInfo.Environment, options.Env, Environment.GetEnvironmentVariables());
45
46            if (options.DumpIO)
47            {
48                Process.ErrorDataReceived += (_, e) => Console.Error.WriteLine(e.Data);
49            }
50        }
51
52        /// <summary>
53        /// Finalizes an instance of the <see cref="LauncherBase"/> class.
54        /// </summary>
55        ~LauncherBase()
56        {
57            Dispose(false);
58        }
59
60        internal TaskCompletionSource<bool> ExitCompletionSource { get; } = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
61
62        internal TaskCompletionSource<string> StartCompletionSource { get; } = new TaskCompletionSource<string>(TaskCreationOptions.RunContinuationsAsynchronously);
63
64        internal LaunchOptions Options { get; }
65
66        /// <summary>
67        /// Gets Base process details.
68        /// </summary>
69        public Process Process { get; }
70
71        /// <summary>
72        /// Gets Base endpoint.
73        /// </summary>
74        public string EndPoint => StartCompletionSource.Task.IsCompleted
75            ? StartCompletionSource.Task.Result
76            : null;
77
78        /// <summary>
79        /// Indicates whether Base process is exiting.
80        /// </summary>
81        public bool IsExiting => _stateManager.CurrentState.IsExiting;
82
83        /// <summary>
84        /// Indicates whether Base process has exited.
85        /// </summary>
86        public bool HasExited => _stateManager.CurrentState.IsExited;
87
88        internal TempDirectory TempUserDataDir { get; set; }
89
90        /// <summary>
91        /// Gets Base process current state.
92        /// </summary>
93        internal State CurrentState => _stateManager.CurrentState;
94
95        /// <inheritdoc />
96        public void Dispose()
97        {
98            Dispose(true);
99            GC.SuppressFinalize(this);
100        }
101
102        /// <summary>
103        /// Disposes Base process and any temporary user directory.
104        /// </summary>
105        /// <param name="disposing">Indicates whether disposal was initiated by <see cref="Dispose()"/> operation.</param>
106        protected virtual void Dispose(bool disposing) => _stateManager.CurrentState.Dispose(this);
107
108        /// <summary>
109        /// Asynchronously starts Base process.
110        /// </summary>
111        /// <returns></returns>
112        public Task StartAsync() => _stateManager.CurrentState.StartAsync(this);
113
114        /// <summary>
115        /// Asynchronously waits for graceful Base process exit within a given timeout period.
116        /// Kills the Base process if it has not exited within this period.
117        /// </summary>
118        /// <param name="timeout">The maximum waiting time for a graceful process exit.</param>
119        /// <returns></returns>
120        public Task EnsureExitAsync(TimeSpan? timeout) => timeout.HasValue
121            ? _stateManager.CurrentState.ExitAsync(this, timeout.Value)
122            : _stateManager.CurrentState.KillAsync(this);
123
124        /// <summary>
125        /// Asynchronously kills Base process.
126        /// </summary>
127        /// <returns></returns>
128        public Task KillAsync() => _stateManager.CurrentState.KillAsync(this);
129
130        /// <summary>
131        /// Waits for Base process exit within a given timeout.
132        /// </summary>
133        /// <param name="timeout">The maximum wait period.</param>
134        /// <returns><c>true</c> if Base process has exited within the given <paramref name="timeout"/>,
135        /// or <c>false</c> otherwise.</returns>
136        public async Task<bool> WaitForExitAsync(TimeSpan? timeout)
137        {
138            if (timeout.HasValue)
139            {
140                var taskCompleted = true;
141                await ExitCompletionSource.Task.WithTimeout(
142                    () =>
143                    {
144                        taskCompleted = false;
145                    },
146                    timeout.Value).ConfigureAwait(false);
147                return taskCompleted;
148            }
149
150            await ExitCompletionSource.Task.ConfigureAwait(false);
151            return true;
152        }
153
154        /// <summary>
155        /// Set Env Variables
156        /// </summary>
157        /// <param name="environment">The environment.</param>
158        /// <param name="customEnv">The customEnv.</param>
159        /// <param name="realEnv">The realEnv.</param>
160        protected static void SetEnvVariables(IDictionary<string, string> environment, IDictionary<string, string> customEnv, IDictionary realEnv)
161        {
162            if (environment == null)
163            {
164                throw new ArgumentNullException(nameof(environment));
165            }
166
167            if (realEnv == null)
168            {
169                throw new ArgumentNullException(nameof(realEnv));
170            }
171
172            foreach (DictionaryEntry item in realEnv)
173            {
174                environment[item.Key.ToString()] = item.Value.ToString();
175            }
176
177            if (customEnv != null)
178            {
179                foreach (var item in customEnv)
180                {
181                    environment[item.Key] = item.Value;
182                }
183            }
184        }
185    }
186}
187
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Trigger StartAsync code on LambdaTest Cloud Grid

Execute automation tests with StartAsync on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)