Skip to content

Commit

Permalink
[dotnet] Configure await false to all awaitable invocations (#12664)
Browse files Browse the repository at this point in the history
  • Loading branch information
nvborisenko committed Sep 7, 2023
1 parent 4dbd6ba commit 8c4f48c
Show file tree
Hide file tree
Showing 22 changed files with 202 additions and 211 deletions.
37 changes: 18 additions & 19 deletions dotnet/src/webdriver/DevTools/DevToolsSession.cs
Expand Up @@ -73,7 +73,6 @@ public DevToolsSession(string endpointAddress)
this.websocketAddress = endpointAddress;
}
this.messageQueueMonitorTask = Task.Run(() => this.MonitorMessageQueue());
this.messageQueueMonitorTask.ConfigureAwait(false);
}

/// <summary>
Expand Down Expand Up @@ -142,7 +141,7 @@ public async Task<ICommandResponse<TCommand>> SendCommand<TCommand>(TCommand com
throw new ArgumentNullException(nameof(command));
}

var result = await SendCommand(command.CommandName, JToken.FromObject(command), cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
var result = await SendCommand(command.CommandName, JToken.FromObject(command), cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived).ConfigureAwait(false);

if (result == null)
{
Expand Down Expand Up @@ -176,7 +175,7 @@ public async Task<ICommandResponse<TCommand>> SendCommand<TCommand>(TCommand com
throw new ArgumentNullException(nameof(command));
}

var result = await SendCommand(command.CommandName, JToken.FromObject(command), cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
var result = await SendCommand(command.CommandName, JToken.FromObject(command), cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived).ConfigureAwait(false);

if (result == null)
{
Expand Down Expand Up @@ -206,7 +205,7 @@ public async Task<JToken> SendCommand(string commandName, JToken commandParamete
if (this.attachedTargetId == null)
{
LogTrace("Session not currently attached to a target; reattaching");
await this.InitializeSession();
await this.InitializeSession().ConfigureAwait(false);
}

var message = new DevToolsCommandData(Interlocked.Increment(ref this.currentCommandId), this.ActiveSessionId, commandName, commandParameters);
Expand All @@ -217,9 +216,9 @@ public async Task<JToken> SendCommand(string commandName, JToken commandParamete

string contents = JsonConvert.SerializeObject(message);
this.pendingCommands.TryAdd(message.CommandId, message);
await this.connection.SendData(contents);
await this.connection.SendData(contents).ConfigureAwait(false);

var responseWasReceived = await Task.Run(() => message.SyncEvent.Wait(millisecondsTimeout.Value, cancellationToken));
var responseWasReceived = message.SyncEvent.Wait(millisecondsTimeout.Value, cancellationToken);

if (!responseWasReceived && throwExceptionIfResponseNotReceived)
{
Expand Down Expand Up @@ -272,15 +271,15 @@ public void Dispose()
/// <returns>A task that represents the asynchronous operation.</returns>
internal async Task StartSession(int requestedProtocolVersion)
{
int protocolVersion = await InitializeProtocol(requestedProtocolVersion);
int protocolVersion = await InitializeProtocol(requestedProtocolVersion).ConfigureAwait(false);
this.domains = DevToolsDomains.InitializeDomains(protocolVersion, this);
await this.InitializeSocketConnection();
await this.InitializeSession();
await this.InitializeSocketConnection().ConfigureAwait(false);
await this.InitializeSession().ConfigureAwait(false);
try
{
// Wrap this in a try-catch, because it's not the end of the
// world if clearing the log doesn't work.
await this.domains.Log.Clear();
await this.domains.Log.Clear().ConfigureAwait(false);
LogTrace("Log cleared.", this.attachedTargetId);
}
catch (WebDriverException)
Expand All @@ -303,7 +302,7 @@ internal async Task StopSession(bool manualDetach)
this.ActiveSessionId = null;
if (manualDetach)
{
await this.Domains.Target.DetachFromTarget(sessionId, this.attachedTargetId);
await this.Domains.Target.DetachFromTarget(sessionId, this.attachedTargetId).ConfigureAwait(false);
}

this.attachedTargetId = null;
Expand Down Expand Up @@ -339,7 +338,7 @@ private async Task<int> InitializeProtocol(int requestedProtocolVersion)
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(debuggerUrl);
rawVersionInfo = await client.GetStringAsync("/json/version");
rawVersionInfo = await client.GetStringAsync("/json/version").ConfigureAwait(false);
}

var versionInfo = JsonConvert.DeserializeObject<DevToolsVersionInfo>(rawVersionInfo);
Expand Down Expand Up @@ -375,7 +374,7 @@ private async Task InitializeSession()
// that when getting the available targets, we won't
// recursively try to call InitializeSession.
this.attachedTargetId = "";
var targets = await this.domains.Target.GetTargets();
var targets = await this.domains.Target.GetTargets().ConfigureAwait(false);
foreach (var target in targets)
{
if (target.Type == "page")
Expand All @@ -393,11 +392,11 @@ private async Task InitializeSession()
throw new WebDriverException("Unable to find target to attach to, no taargets of type 'page' available");
}

string sessionId = await this.domains.Target.AttachToTarget(this.attachedTargetId);
string sessionId = await this.domains.Target.AttachToTarget(this.attachedTargetId).ConfigureAwait(false);
LogTrace("Target ID {0} attached. Active session ID: {1}", this.attachedTargetId, sessionId);
this.ActiveSessionId = sessionId;

await this.domains.Target.SetAutoAttach();
await this.domains.Target.SetAutoAttach().ConfigureAwait(false);
LogTrace("AutoAttach is set.", this.attachedTargetId);

this.domains.Target.TargetDetached += this.OnTargetDetached;
Expand All @@ -416,7 +415,7 @@ private async Task InitializeSocketConnection()
LogTrace("Creating WebSocket");
this.connection = new WebSocketConnection(this.openConnectionWaitTimeSpan, this.closeConnectionWaitTimeSpan);
connection.DataReceived += OnConnectionDataReceived;
await connection.Start(this.websocketAddress);
await connection.Start(this.websocketAddress).ConfigureAwait(false);
LogTrace("WebSocket created");
}

Expand All @@ -425,8 +424,8 @@ private async Task TerminateSocketConnection()
LogTrace("Closing WebSocket");
if (this.connection != null && this.connection.IsActive)
{
await this.connection.Stop();
await this.ShutdownMessageQueue();
await this.connection.Stop().ConfigureAwait(false);
await this.ShutdownMessageQueue().ConfigureAwait(false);
}
LogTrace("WebSocket closed");
}
Expand All @@ -443,7 +442,7 @@ private async Task ShutdownMessageQueue()
}

this.messageQueue.CompleteAdding();
await this.messageQueueMonitorTask;
await this.messageQueueMonitorTask.ConfigureAwait(false);
}

private void MonitorMessageQueue()
Expand Down
2 changes: 1 addition & 1 deletion dotnet/src/webdriver/DevTools/Network.cs
Expand Up @@ -78,7 +78,7 @@ public abstract class Network
/// <returns>A task that represents the asynchronous operation.</returns>
public async Task SetUserAgentOverride(string userAgent)
{
await SetUserAgentOverride(new UserAgent() { UserAgentString = userAgent });
await SetUserAgentOverride(new UserAgent() { UserAgentString = userAgent }).ConfigureAwait(false);
}

/// <summary>
Expand Down
18 changes: 9 additions & 9 deletions dotnet/src/webdriver/DevTools/WebSocketConnection.cs
Expand Up @@ -102,14 +102,14 @@ public virtual async Task Start(string url)
{
try
{
await this.client.ConnectAsync(new Uri(url), this.clientTokenSource.Token);
await this.client.ConnectAsync(new Uri(url), this.clientTokenSource.Token).ConfigureAwait(false);
connected = true;
}
catch (WebSocketException)
{
// If the server-side socket is not yet ready, it leaves the client socket in a closed state,
// which sees the object as disposed, so we must create a new one to try again
await Task.Delay(TimeSpan.FromMilliseconds(500));
await Task.Delay(TimeSpan.FromMilliseconds(500)).ConfigureAwait(false);
this.client = new ClientWebSocket();
}
}
Expand Down Expand Up @@ -137,15 +137,15 @@ public virtual async Task Stop()
}
else
{
await this.CloseClientWebSocket();
await this.CloseClientWebSocket().ConfigureAwait(false);
}

// Whether we closed the socket or timed out, we cancel the token causing ReceiveAsync to abort the socket.
// The finally block at the end of the processing loop will dispose of the ClientWebSocket object.
this.clientTokenSource.Cancel();
if (this.dataReceiveTask != null)
{
await this.dataReceiveTask;
await this.dataReceiveTask.ConfigureAwait(false);
}

this.client.Dispose();
Expand All @@ -165,7 +165,7 @@ public virtual async Task SendData(string data)

try
{
await this.client.SendAsync(messageBuffer, WebSocketMessageType.Text, endOfMessage: true, CancellationToken.None);
await this.client.SendAsync(messageBuffer, WebSocketMessageType.Text, endOfMessage: true, CancellationToken.None).ConfigureAwait(false);
}
finally
{
Expand All @@ -184,13 +184,13 @@ protected virtual async Task CloseClientWebSocket()
try
{
// After this, the socket state which change to CloseSent
await this.client.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "Closing", timeout.Token);
await this.client.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "Closing", timeout.Token).ConfigureAwait(false);

// Now we wait for the server response, which will close the socket
while (this.client.State != WebSocketState.Closed && this.client.State != WebSocketState.Aborted && !timeout.Token.IsCancellationRequested)
{
// The loop may be too tight for the cancellation token to get triggered, so add a small delay
await Task.Delay(TimeSpan.FromMilliseconds(10));
await Task.Delay(TimeSpan.FromMilliseconds(10)).ConfigureAwait(false);
}

this.Log($"Client state is {this.client.State}", DevToolsSessionLogLevel.Trace);
Expand Down Expand Up @@ -238,7 +238,7 @@ private async Task ReceiveData()
ArraySegment<byte> buffer = WebSocket.CreateClientBuffer(this.bufferSize, this.bufferSize);
while (this.client.State != WebSocketState.Closed && !cancellationToken.IsCancellationRequested)
{
WebSocketReceiveResult receiveResult = await this.client.ReceiveAsync(buffer, cancellationToken);
WebSocketReceiveResult receiveResult = await this.client.ReceiveAsync(buffer, cancellationToken).ConfigureAwait(false);

// If the token is cancelled while ReceiveAsync is blocking, the socket state changes to aborted and it can't be used
if (!cancellationToken.IsCancellationRequested)
Expand All @@ -248,7 +248,7 @@ private async Task ReceiveData()
if (receiveResult.MessageType == WebSocketMessageType.Close && this.client.State != WebSocketState.Closed && this.client.State != WebSocketState.CloseSent)
{
this.Log($"Acknowledging Close frame received from server (client state: {this.client.State})", DevToolsSessionLogLevel.Trace);
await this.client.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "Acknowledge Close frame", CancellationToken.None);
await this.client.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "Acknowledge Close frame", CancellationToken.None).ConfigureAwait(false);
}

// Display text or binary data
Expand Down
18 changes: 9 additions & 9 deletions dotnet/src/webdriver/DevTools/v114/V114JavaScript.cs
Expand Up @@ -51,7 +51,7 @@ public V114JavaScript(RuntimeAdapter runtime, PageAdapter page)
/// <returns>A task that represents the asynchronous operation.</returns>
public override async Task EnableRuntime()
{
await runtime.Enable();
await runtime.Enable().ConfigureAwait(false);
}

/// <summary>
Expand All @@ -60,7 +60,7 @@ public override async Task EnableRuntime()
/// <returns>A task that represents the asynchronous operation.</returns>
public override async Task DisableRuntime()
{
await runtime.Disable();
await runtime.Disable().ConfigureAwait(false);
}

/// <summary>
Expand All @@ -69,7 +69,7 @@ public override async Task DisableRuntime()
/// <returns>A task that represents the asynchronous operation.</returns>
public override async Task EnablePage()
{
await page.Enable();
await page.Enable().ConfigureAwait(false);
}

/// <summary>
Expand All @@ -78,7 +78,7 @@ public override async Task EnablePage()
/// <returns>A task that represents the asynchronous operation.</returns>
public override async Task DisablePage()
{
await page.Disable();
await page.Disable().ConfigureAwait(false);
}

/// <summary>
Expand All @@ -88,7 +88,7 @@ public override async Task DisablePage()
/// <returns>A task that represents the asynchronous operation.</returns>
public override async Task AddBinding(string name)
{
await runtime.AddBinding(new AddBindingCommandSettings() { Name = name });
await runtime.AddBinding(new AddBindingCommandSettings() { Name = name }).ConfigureAwait(false);
}

/// <summary>
Expand All @@ -98,7 +98,7 @@ public override async Task AddBinding(string name)
/// <returns>A task that represents the asynchronous operation.</returns>
public override async Task RemoveBinding(string name)
{
await runtime.RemoveBinding(new RemoveBindingCommandSettings() { Name = name });
await runtime.RemoveBinding(new RemoveBindingCommandSettings() { Name = name }).ConfigureAwait(false);
}

/// <summary>
Expand All @@ -108,7 +108,7 @@ public override async Task RemoveBinding(string name)
/// <returns>A task that represents the asynchronous operation. The task result contains the internal ID of the script.</returns>
public override async Task<string> AddScriptToEvaluateOnNewDocument(string script)
{
var result = await page.AddScriptToEvaluateOnNewDocument(new AddScriptToEvaluateOnNewDocumentCommandSettings() { Source = script });
var result = await page.AddScriptToEvaluateOnNewDocument(new AddScriptToEvaluateOnNewDocumentCommandSettings() { Source = script }).ConfigureAwait(false);
return result.Identifier;
}

Expand All @@ -119,7 +119,7 @@ public override async Task<string> AddScriptToEvaluateOnNewDocument(string scrip
/// <returns>A task that represents the asynchronous operation.</returns>
public override async Task RemoveScriptToEvaluateOnNewDocument(string scriptId)
{
await page.RemoveScriptToEvaluateOnNewDocument(new RemoveScriptToEvaluateOnNewDocumentCommandSettings() { Identifier = scriptId });
await page.RemoveScriptToEvaluateOnNewDocument(new RemoveScriptToEvaluateOnNewDocumentCommandSettings() { Identifier = scriptId }).ConfigureAwait(false);
}

/// <summary>
Expand All @@ -133,7 +133,7 @@ public override async Task RemoveScriptToEvaluateOnNewDocument(string scriptId)
/// </remarks>
internal override async Task Evaluate(string script)
{
await runtime.Evaluate(new EvaluateCommandSettings { Expression = script });
await runtime.Evaluate(new EvaluateCommandSettings { Expression = script }).ConfigureAwait(false);
}

private void OnRuntimeBindingCalled(object sender, Runtime.BindingCalledEventArgs e)
Expand Down
6 changes: 3 additions & 3 deletions dotnet/src/webdriver/DevTools/v114/V114Log.cs
Expand Up @@ -47,7 +47,7 @@ public V114Log(LogAdapter adapter)
/// <returns>A task that represents the asynchronous operation.</returns>
public override async Task Enable()
{
await adapter.Enable();
await adapter.Enable().ConfigureAwait(false);
}

/// <summary>
Expand All @@ -56,7 +56,7 @@ public override async Task Enable()
/// <returns>A task that represents the asynchronous operation.</returns>
public override async Task Disable()
{
await adapter.Disable();
await adapter.Disable().ConfigureAwait(false);
}

/// <summary>
Expand All @@ -65,7 +65,7 @@ public override async Task Disable()
/// <returns>A task that represents the asynchronous operation.</returns>
public override async Task Clear()
{
await adapter.Clear();
await adapter.Clear().ConfigureAwait(false);
}

private void OnAdapterEntryAdded(object sender, Log.EntryAddedEventArgs e)
Expand Down

0 comments on commit 8c4f48c

Please sign in to comment.