Skip to content

Commit

Permalink
chore: Add ConfigureAwait to all points in library code
Browse files Browse the repository at this point in the history
Also, add more configureawait exceptions for tests and tutorials

Fixes #522
  • Loading branch information
qdot committed Nov 2, 2018
1 parent 4982eed commit 976e1ac
Show file tree
Hide file tree
Showing 35 changed files with 208 additions and 184 deletions.
Expand Up @@ -55,9 +55,9 @@ public async Task ConnectAsync(CancellationToken aToken = default(CancellationTo
PipeDirection.InOut, PipeOptions.Asynchronous,
TokenImpersonationLevel.Impersonation);

await _pipeClient.ConnectAsync(aToken);
await _pipeClient.ConnectAsync(aToken).ConfigureAwait(false);

_readTask = new Task(async () => { await pipeReader(aToken); },
_readTask = new Task(async () => { await pipeReader(aToken).ConfigureAwait(false); },
aToken,
TaskCreationOptions.LongRunning);
_readTask.Start();
Expand All @@ -68,7 +68,7 @@ public async Task DisconnectAsync(CancellationToken aToken = default(Cancellatio
// TODO Create internal token for cancellation and use link source with external key
//_cancellationToken.Cancel();
_pipeClient.Close();
await _readTask;
await _readTask.ConfigureAwait(false);
}

public async Task<ButtplugMessage> SendAsync(ButtplugMessage aMsg, CancellationToken aToken = default(CancellationToken))
Expand All @@ -88,7 +88,7 @@ public async Task<ButtplugMessage> SendAsync(ButtplugMessage aMsg, CancellationT
}
}

return await promise;
return await promise.ConfigureAwait(false);
}

private async Task pipeReader(CancellationToken aCancellationToken)
Expand All @@ -102,7 +102,7 @@ private async Task pipeReader(CancellationToken aCancellationToken)
{
try
{
len = await _pipeClient.ReadAsync(buffer, 0, buffer.Length, aCancellationToken);
len = await _pipeClient.ReadAsync(buffer, 0, buffer.Length, aCancellationToken).ConfigureAwait(false);
}
catch
{
Expand Down
Expand Up @@ -78,14 +78,14 @@ public async Task ConnectAsync(CancellationToken aToken = default(CancellationTo

try
{
_ws = await _wsClient.ConnectAsync(_uri, aToken);
_ws = await _wsClient.ConnectAsync(_uri, aToken).ConfigureAwait(false);
}
catch (Exception e)
{
throw new ButtplugClientConnectorException(_logger, "Websocket Connection Exception! See Inner Exception", e);
}

_readTask = new Task(async () => { await RunClientLoop(aToken); },
_readTask = new Task(async () => { await RunClientLoop(aToken).ConfigureAwait(false); },
aToken,
TaskCreationOptions.LongRunning);
_readTask.Start();
Expand All @@ -101,7 +101,7 @@ public async Task DisconnectAsync(CancellationToken aToken = default(Cancellatio
{
if (_ws != null && _ws.IsConnected)
{
await _ws.CloseAsync();
await _ws.CloseAsync().ConfigureAwait(false);
}
}
catch
Expand All @@ -110,14 +110,14 @@ public async Task DisconnectAsync(CancellationToken aToken = default(Cancellatio
}

// If we have a live task, wait for it to shut down and fire the disconnection event
await _readTask;
await _readTask.ConfigureAwait(false);
}

public async Task<ButtplugMessage> SendAsync(ButtplugMessage aMsg, CancellationToken aToken)
{
var (msgString, msgPromise) = PrepareMessage(aMsg);
await _outgoingMessages.SendAsync(msgString, aToken);
return await msgPromise;
await _outgoingMessages.SendAsync(msgString, aToken).ConfigureAwait(false);
return await msgPromise.ConfigureAwait(false);
}

private async Task RunClientLoop(CancellationToken aToken)
Expand All @@ -138,7 +138,7 @@ private async Task RunClientLoop(CancellationToken aToken)

if (completedTaskIndex == 0)
{
var incomingMsg = await (Task<string>) msgTasks[0];
var incomingMsg = await ((Task<string>) msgTasks[0]).ConfigureAwait(false);
if (incomingMsg != null)
{
ReceiveMessages(incomingMsg);
Expand All @@ -155,7 +155,7 @@ private async Task RunClientLoop(CancellationToken aToken)
var outMsgs = msgs.Aggregate(string.Empty, (current, msg) => current + msg);
if (_ws != null && _ws.IsConnected)
{
await _ws.WriteStringAsync(outMsgs, aToken);
await _ws.WriteStringAsync(outMsgs, aToken).ConfigureAwait(false);
}

writeTask = _outgoingMessages.OutputAvailableAsync(aToken);
Expand Down
34 changes: 17 additions & 17 deletions Buttplug.Client/ButtplugClient.cs
Expand Up @@ -160,9 +160,9 @@ public async Task ConnectAsync(CancellationToken aToken = default(CancellationTo
}

_connector.MessageReceived += MessageReceivedHandler;
await _connector.ConnectAsync(aToken);
await _connector.ConnectAsync(aToken).ConfigureAwait(false);

var res = await SendMessageAsync(new RequestServerInfo(Name), aToken);
var res = await SendMessageAsync(new RequestServerInfo(Name), aToken).ConfigureAwait(false);
switch (res)
{
case ServerInfo si:
Expand All @@ -174,17 +174,17 @@ public async Task ConnectAsync(CancellationToken aToken = default(CancellationTo

if (si.MessageVersion < ButtplugConsts.CurrentSpecVersion)
{
await DisconnectAsync();
await DisconnectAsync().ConfigureAwait(false);
throw new ButtplugHandshakeException(_bpLogger,
$"Buttplug Server's schema version ({si.MessageVersion}) is less than the client's ({ButtplugConsts.CurrentSpecVersion}). A newer server is required.",
res.Id);
}

// Get full device list and populate internal list
var resp = await SendMessageAsync(new RequestDeviceList());
var resp = await SendMessageAsync(new RequestDeviceList()).ConfigureAwait(false);
if (!(resp is DeviceList))
{
await DisconnectAsync();
await DisconnectAsync().ConfigureAwait(false);
if (resp is Error errResp)
{
throw ButtplugException.FromError(_bpLogger, errResp);
Expand All @@ -209,11 +209,11 @@ public async Task ConnectAsync(CancellationToken aToken = default(CancellationTo
break;

case Error e:
await DisconnectAsync();
await DisconnectAsync().ConfigureAwait(false);
throw ButtplugException.FromError(_bpLogger, e);

default:
await DisconnectAsync();
await DisconnectAsync().ConfigureAwait(false);
throw new ButtplugHandshakeException(_bpLogger, $"Unrecognized message {res.Name} during handshake", res.Id);
}
}
Expand All @@ -226,7 +226,7 @@ public async Task DisconnectAsync()
}

_connector.MessageReceived -= MessageReceivedHandler;
await _connector.DisconnectAsync();
await _connector.DisconnectAsync().ConfigureAwait(false);
ServerDisconnect?.Invoke(this, new EventArgs());
}

Expand All @@ -242,7 +242,7 @@ public async Task DisconnectAsync()
// ReSharper disable once UnusedMember.Global
public async Task StartScanningAsync(CancellationToken aToken = default(CancellationToken))
{
await SendMessageExpectOk(new StartScanning(), aToken);
await SendMessageExpectOk(new StartScanning(), aToken).ConfigureAwait(false);
}

/// <summary>
Expand All @@ -256,7 +256,7 @@ public async Task StartScanningAsync(CancellationToken aToken = default(Cancella
// ReSharper disable once UnusedMember.Global
public async Task StopScanningAsync(CancellationToken aToken = default(CancellationToken))
{
await SendMessageExpectOk(new StopScanning(), aToken);
await SendMessageExpectOk(new StopScanning(), aToken).ConfigureAwait(false);
}

/// <summary>
Expand All @@ -271,7 +271,7 @@ public async Task StopScanningAsync(CancellationToken aToken = default(Cancellat
// ReSharper disable once UnusedMember.Global
public async Task RequestLogAsync(ButtplugLogLevel aLogLevel, CancellationToken aToken = default(CancellationToken))
{
await SendMessageExpectOk(new RequestLog(aLogLevel), aToken);
await SendMessageExpectOk(new RequestLog(aLogLevel), aToken).ConfigureAwait(false);
}

/// <summary>
Expand All @@ -286,7 +286,7 @@ public async Task RequestLogAsync(ButtplugLogLevel aLogLevel, CancellationToken
/// </returns>
protected async Task SendDeviceMessageAsync(ButtplugClientDevice aDevice, ButtplugDeviceMessage aDeviceMsg, CancellationToken aToken = default(CancellationToken))
{
await SendMessageExpectOk(aDeviceMsg, aToken);
await SendMessageExpectOk(aDeviceMsg, aToken).ConfigureAwait(false);
}

/// <summary>
Expand All @@ -302,7 +302,7 @@ protected async Task<ButtplugMessage> SendMessageAsync(ButtplugMessage aMsg, Can
throw new ButtplugClientConnectorException(_bpLogger, "Client not connected.");
}

return await _connector.SendAsync(aMsg, aToken);
return await _connector.SendAsync(aMsg, aToken).ConfigureAwait(false);
}

private void ConnectorErrorHandler(object aSender, ButtplugExceptionEventArgs aException)
Expand Down Expand Up @@ -361,7 +361,7 @@ private async void MessageReceivedHandler(object aSender, MessageReceivedEventAr
if (e.ErrorCode == Error.ErrorClass.ERROR_PING)
{
PingTimeout?.Invoke(this, EventArgs.Empty);
await DisconnectAsync();
await DisconnectAsync().ConfigureAwait(false);
}

break;
Expand All @@ -386,14 +386,14 @@ private async void OnPingTimer(object aState)
{
try
{
await SendMessageExpectOk(new Ping());
await SendMessageExpectOk(new Ping()).ConfigureAwait(false);
}
catch (Exception e)
{
ErrorReceived?.Invoke(_bpLogger, new ButtplugExceptionEventArgs(new ButtplugPingException(_bpLogger, "Exception thrown during ping update", ButtplugConsts.SystemMsgId, e)));

// If SendMessageAsync throws, we're probably already disconnected, but just make sure.
await DisconnectAsync();
await DisconnectAsync().ConfigureAwait(false);
}
}

Expand All @@ -405,7 +405,7 @@ private async void OnPingTimer(object aState)
/// <returns>True if successful.</returns>
private async Task SendMessageExpectOk(ButtplugMessage aMsg, CancellationToken aToken = default(CancellationToken))
{
var msg = await SendMessageAsync(aMsg, aToken);
var msg = await SendMessageAsync(aMsg, aToken).ConfigureAwait(false);
switch (msg)
{
case Ok _:
Expand Down
24 changes: 12 additions & 12 deletions Buttplug.Client/ButtplugClientDevice.cs
Expand Up @@ -144,7 +144,7 @@ public async Task SendMessageAsync(ButtplugDeviceMessage aMsg, CancellationToken

aMsg.DeviceIndex = Index;

await _sendClosure(this, aMsg, aToken);
await _sendClosure(this, aMsg, aToken).ConfigureAwait(false);
}

public bool Equals(ButtplugClientDevice aDevice)
Expand Down Expand Up @@ -205,74 +205,74 @@ private void CheckAllowedMessageType<T>()
public async Task SendVibrateCmd(double aSpeed)
{
CheckAllowedMessageType<VibrateCmd>();
await SendMessageAsync(VibrateCmd.Create(aSpeed, GetMessageAttributes<VibrateCmd>().FeatureCount.Value));
await SendMessageAsync(VibrateCmd.Create(aSpeed, GetMessageAttributes<VibrateCmd>().FeatureCount.Value)).ConfigureAwait(false);
}

public async Task SendVibrateCmd(IEnumerable<double> aCmds)
{
CheckAllowedMessageType<VibrateCmd>();
var msg = VibrateCmd.Create(aCmds);
CheckGenericSubcommandList(msg.Speeds, GetMessageAttributes<VibrateCmd>().FeatureCount.Value);
await SendMessageAsync(VibrateCmd.Create(aCmds));
await SendMessageAsync(VibrateCmd.Create(aCmds)).ConfigureAwait(false);
}

public async Task SendRotateCmd(double aSpeed, bool aClockwise)
{
CheckAllowedMessageType<RotateCmd>();
await SendMessageAsync(RotateCmd.Create(aSpeed, aClockwise, GetMessageAttributes<RotateCmd>().FeatureCount.Value));
await SendMessageAsync(RotateCmd.Create(aSpeed, aClockwise, GetMessageAttributes<RotateCmd>().FeatureCount.Value)).ConfigureAwait(false);
}

public async Task SendRotateCmd(IEnumerable<(double, bool)> aCmds)
{
CheckAllowedMessageType<RotateCmd>();
var msg = RotateCmd.Create(aCmds);
CheckGenericSubcommandList(msg.Rotations, GetMessageAttributes<RotateCmd>().FeatureCount.Value);
await SendMessageAsync(RotateCmd.Create(aCmds));
await SendMessageAsync(RotateCmd.Create(aCmds)).ConfigureAwait(false);
}

public async Task SendLinearCmd(uint aDuration, double aPosition)
{
CheckAllowedMessageType<LinearCmd>();
await SendMessageAsync(LinearCmd.Create(aDuration, aPosition, GetMessageAttributes<LinearCmd>().FeatureCount.Value));
await SendMessageAsync(LinearCmd.Create(aDuration, aPosition, GetMessageAttributes<LinearCmd>().FeatureCount.Value)).ConfigureAwait(false);
}

public async Task SendLinearCmd(IEnumerable<(uint, double)> aCmds)
{
CheckAllowedMessageType<LinearCmd>();
var msg = LinearCmd.Create(aCmds);
CheckGenericSubcommandList(msg.Vectors, GetMessageAttributes<LinearCmd>().FeatureCount.Value);
await SendMessageAsync(LinearCmd.Create(aCmds));
await SendMessageAsync(LinearCmd.Create(aCmds)).ConfigureAwait(false);
}

public async Task SendFleshlightLaunchFW12Cmd(uint aSpeed, uint aPosition)
{
CheckAllowedMessageType<FleshlightLaunchFW12Cmd>();
await SendMessageAsync(new FleshlightLaunchFW12Cmd(Index, aSpeed, aPosition));
await SendMessageAsync(new FleshlightLaunchFW12Cmd(Index, aSpeed, aPosition)).ConfigureAwait(false);
}

public async Task SendLovenseCmd(string aDeviceCmd)
{
CheckAllowedMessageType<LovenseCmd>();
await SendMessageAsync(new LovenseCmd(Index, aDeviceCmd));
await SendMessageAsync(new LovenseCmd(Index, aDeviceCmd)).ConfigureAwait(false);
}

public async Task SendVorzeA10CycloneCmd(uint aSpeed, bool aClockwise)
{
CheckAllowedMessageType<VorzeA10CycloneCmd>();
await SendMessageAsync(new VorzeA10CycloneCmd(Index, aSpeed, aClockwise));
await SendMessageAsync(new VorzeA10CycloneCmd(Index, aSpeed, aClockwise)).ConfigureAwait(false);
}

public async Task StopDeviceCmd()
{
// Every message should support this, but it doesn't hurt to check
CheckAllowedMessageType<StopDeviceCmd>();
await SendMessageAsync(new StopDeviceCmd(Index));
await SendMessageAsync(new StopDeviceCmd(Index)).ConfigureAwait(false);
}

public async Task KiirooCmd(uint aPosition)
{
CheckAllowedMessageType<KiirooCmd>();
await SendMessageAsync(new KiirooCmd(Index, aPosition));
await SendMessageAsync(new KiirooCmd(Index, aPosition)).ConfigureAwait(false);
}
}
}
2 changes: 1 addition & 1 deletion Buttplug.Client/ButtplugEmbeddedConnector.cs
Expand Up @@ -69,7 +69,7 @@ public Task DisconnectAsync(CancellationToken aToken = default(CancellationToken

public async Task<ButtplugMessage> SendAsync(ButtplugMessage aMsg, CancellationToken aToken = default(CancellationToken))
{
return await Server.SendMessageAsync(aMsg);
return await Server.SendMessageAsync(aMsg).ConfigureAwait(false);
}

private void OnServerMessageReceived(object e, MessageReceivedEventArgs aMsgEvent)
Expand Down
2 changes: 1 addition & 1 deletion Buttplug.Core/Devices/ButtplugDevice.cs
Expand Up @@ -99,7 +99,7 @@ public async Task<ButtplugMessage> ParseMessageAsync([NotNull] ButtplugDeviceMes

// We just checked whether the key exists above, so we're ok.
// ReSharper disable once PossibleNullReferenceException
return await MsgFuncs[aMsg.GetType()].Function.Invoke(aMsg, aToken);
return await MsgFuncs[aMsg.GetType()].Function.Invoke(aMsg, aToken).ConfigureAwait(false);
}

/// <inheritdoc />
Expand Down
3 changes: 3 additions & 0 deletions Buttplug.Examples.01.EmbeddedClientSetup/Program.cs
@@ -1,6 +1,9 @@
using System.Threading.Tasks;
using Buttplug.Client;

// Tutorial file, disable ConfigureAwait checking since it's an actual program.
// ReSharper disable ConsiderUsingConfigureAwait

namespace Buttplug.Examples.EmbeddedClientSetup
{
internal class Program
Expand Down
3 changes: 3 additions & 0 deletions Buttplug.Examples.02.WebsocketClientSetup/Program.cs
Expand Up @@ -3,6 +3,9 @@
using Buttplug.Client;
using Buttplug.Client.Connectors.WebsocketConnector;

// Tutorial file, disable ConfigureAwait checking since it's an actual program.
// ReSharper disable ConsiderUsingConfigureAwait

namespace Buttplug.Examples._02.WebsocketClientSetup
{
internal class Program
Expand Down
Expand Up @@ -3,6 +3,9 @@
using System.Threading.Tasks;
using Buttplug.Client;

// Tutorial file, disable ConfigureAwait checking since it's an actual program.
// ReSharper disable ConsiderUsingConfigureAwait

namespace Buttplug.Examples._03.ConnectionLifetimesAndPingTimers
{
class Program
Expand Down
3 changes: 3 additions & 0 deletions Buttplug.Examples.04.DeviceEnumeration/Program.cs
Expand Up @@ -5,6 +5,9 @@
using Buttplug.Core.Test;
using Buttplug.Server.Test;

// Tutorial file, disable ConfigureAwait checking since it's an actual program.
// ReSharper disable ConsiderUsingConfigureAwait

namespace Buttplug.Examples._03.DeviceEnumeration
{
class Program
Expand Down
3 changes: 3 additions & 0 deletions Buttplug.Examples.05.DeviceControl/Program.cs
Expand Up @@ -7,6 +7,9 @@
using Buttplug.Core.Test;
using Buttplug.Server.Test;

// Tutorial file, disable ConfigureAwait checking since it's an actual program.
// ReSharper disable ConsiderUsingConfigureAwait

namespace Buttplug.Examples._05.DeviceControl
{
class Program
Expand Down

0 comments on commit 976e1ac

Please sign in to comment.