Skip to content

Commit a211198

Browse files
committed
Apply ConfigureAwait(false) and Argument.ThrowIfNull
1 parent d928b31 commit a211198

12 files changed

+47
-56
lines changed

src/Imageflow/Bindings/JobContext.cs

+3-12
Original file line numberDiff line numberDiff line change
@@ -451,10 +451,7 @@ public void AddInputBytes(int ioId, ArraySegment<byte> buffer)
451451
/// <exception cref="ArgumentOutOfRangeException"></exception>
452452
public void AddInputBytes(int ioId, byte[] buffer, long offset, long count)
453453
{
454-
if (buffer == null)
455-
{
456-
throw new ArgumentNullException(nameof(buffer));
457-
}
454+
Argument.ThrowIfNull(buffer);
458455

459456
if (offset > int.MaxValue)
460457
{
@@ -520,10 +517,7 @@ public void AddInputBytes(int ioId, ReadOnlySpan<byte> data)
520517
/// <exception cref="ArgumentNullException"></exception>
521518
public void AddInputBytesPinned(int ioId, byte[] buffer)
522519
{
523-
if (buffer == null)
524-
{
525-
throw new ArgumentNullException(nameof(buffer));
526-
}
520+
Argument.ThrowIfNull(buffer);
527521

528522
AddInputBytesPinned(ioId, new ReadOnlyMemory<byte>(buffer), MemoryLifetimePromise.MemoryIsOwnedByRuntime);
529523
}
@@ -553,10 +547,7 @@ public void AddInputBytesPinned(int ioId, ArraySegment<byte> buffer)
553547
/// <exception cref="ArgumentOutOfRangeException"></exception>
554548
public void AddInputBytesPinned(int ioId, byte[] buffer, long offset, long count)
555549
{
556-
if (buffer == null)
557-
{
558-
throw new ArgumentNullException(nameof(buffer));
559-
}
550+
Argument.ThrowIfNull(buffer);
560551

561552
if (offset > int.MaxValue)
562553
{

src/Imageflow/Fluent/BufferedStreamSource.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ public async ValueTask<ReadOnlyMemory<byte>> BorrowReadOnlyMemoryAsync(Cancellat
8383
_underlying.Seek(0, SeekOrigin.Begin);
8484
}
8585
_copy = new RecyclableMemoryStream(Mgr, "BufferedStreamSource: IMemorySource", _underlying.CanSeek ? _underlying.Length : 0);
86-
await _underlying.CopyToAsync(_copy, 81920, cancellationToken);
86+
await _underlying.CopyToAsync(_copy, 81920, cancellationToken).ConfigureAwait(false);
8787
_copy.Seek(0, SeekOrigin.Begin);
8888
if (!TryGetWrittenMemory(out segment))
8989
{

src/Imageflow/Fluent/FinishJobBuilder.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@ public async Task<BuildJobResult> InProcessAndDisposeAsync()
8989
BuildJobResult r;
9090
try
9191
{
92-
r = await InProcessAsync();
92+
r = await InProcessAsync().ConfigureAwait(false);
9393
}
9494
finally
9595
{

src/Imageflow/Fluent/IOutputDestinationExtensions.cs

+9-9
Original file line numberDiff line numberDiff line change
@@ -25,14 +25,14 @@ internal static async ValueTask AdaptiveWriteAllAsync(this IOutputDestination de
2525
{
2626
if (dest is IAsyncOutputSink sink)
2727
{
28-
await sink.FastRequestCapacityAsync(data.Length);
29-
await sink.FastWriteAsync(data, cancellationToken);
30-
await sink.FastFlushAsync(cancellationToken);
28+
await sink.FastRequestCapacityAsync(data.Length).ConfigureAwait(false);
29+
await sink.FastWriteAsync(data, cancellationToken).ConfigureAwait(false);
30+
await sink.FastFlushAsync(cancellationToken).ConfigureAwait(false);
3131
return;
3232
}
33-
await dest.RequestCapacityAsync(data.Length);
34-
await dest.AdaptedWriteAsync(data, cancellationToken);
35-
await dest.FlushAsync(cancellationToken);
33+
await dest.RequestCapacityAsync(data.Length).ConfigureAwait(false);
34+
await dest.AdaptedWriteAsync(data, cancellationToken).ConfigureAwait(false);
35+
await dest.FlushAsync(cancellationToken).ConfigureAwait(false);
3636
}
3737

3838
internal static async ValueTask AdaptedWriteAsync(this IOutputDestination dest, ReadOnlyMemory<byte> data, CancellationToken cancellationToken)
@@ -86,14 +86,14 @@ internal static void AdaptedWrite(this IOutputDestination dest, ReadOnlySpan<byt
8686
[Obsolete("Users should not write to IOutputDestination directly; this is only for Imageflow internal use.")]
8787
public static async Task CopyFromStreamAsync(this IOutputDestination dest, Stream stream,
8888
CancellationToken cancellationToken)
89-
=> await dest.CopyFromStreamAsyncInternal(stream, cancellationToken);
89+
=> await dest.CopyFromStreamAsyncInternal(stream, cancellationToken).ConfigureAwait(false);
9090

9191
internal static async Task CopyFromStreamAsyncInternal(this IOutputDestination dest, Stream stream,
9292
CancellationToken cancellationToken)
9393
{
9494
if (stream is { CanRead: true, CanSeek: true })
9595
{
96-
await dest.RequestCapacityAsync((int)stream.Length);
96+
await dest.RequestCapacityAsync((int)stream.Length).ConfigureAwait(false);
9797
}
9898

9999
const int bufferSize = 81920;
@@ -107,6 +107,6 @@ await dest.WriteAsync(new ArraySegment<byte>(buffer, 0, bytesRead), cancellation
107107
.ConfigureAwait(false);
108108
}
109109

110-
await dest.FlushAsync(cancellationToken);
110+
await dest.FlushAsync(cancellationToken).ConfigureAwait(false);
111111
}
112112
}

src/Imageflow/Fluent/IOutputSink.cs

+3-3
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,8 @@ internal static class OutputSinkExtensions
1818
{
1919
public static async ValueTask WriteAllAsync(this IAsyncOutputSink sink, ReadOnlyMemory<byte> data, CancellationToken cancellationToken)
2020
{
21-
await sink.FastRequestCapacityAsync(data.Length);
22-
await sink.FastWriteAsync(data, cancellationToken);
23-
await sink.FastFlushAsync(cancellationToken);
21+
await sink.FastRequestCapacityAsync(data.Length).ConfigureAwait(false);
22+
await sink.FastWriteAsync(data, cancellationToken).ConfigureAwait(false);
23+
await sink.FastFlushAsync(cancellationToken).ConfigureAwait(false);
2424
}
2525
}

src/Imageflow/Fluent/ImageJob.cs

+20-20
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ internal void AddInput(int ioId, IAsyncMemorySource source)
2323
{
2424
if (_inputs.ContainsKey(ioId) || _outputs.ContainsKey(ioId))
2525
{
26-
throw new ArgumentException("ioId", $"ioId {ioId} has already been assigned");
26+
throw new ArgumentException($"ioId {ioId} has already been assigned", nameof(ioId));
2727
}
2828

2929
_inputs.Add(ioId, source);
@@ -32,7 +32,7 @@ internal void AddOutput(int ioId, IOutputDestination destination)
3232
{
3333
if (_inputs.ContainsKey(ioId) || _outputs.ContainsKey(ioId))
3434
{
35-
throw new ArgumentException("ioId", $"ioId {ioId} has already been assigned");
35+
throw new ArgumentException($"ioId {ioId} has already been assigned", nameof(ioId));
3636
}
3737

3838
_outputs.Add(ioId, destination);
@@ -148,7 +148,7 @@ public BuildEndpoint BuildCommandString(IBytesSource source, int? sourceIoId, IO
148148
public BuildEndpoint BuildCommandString(byte[] source, IOutputDestination dest, string commandString) => BuildCommandString(new MemorySource(source), dest, commandString);
149149

150150
/// <summary>
151-
/// Modify the input image (source) with the given command string and watermarks and encode to the (dest)
151+
/// Modify the input image (source) with the given command string and watermarks and encode to the (dest)
152152
/// </summary>
153153
/// <param name="source"></param>
154154
/// <param name="dest"></param>
@@ -265,7 +265,7 @@ internal string ToJsonDebug(SecurityOptions? securityOptions = default)
265265
internal async Task<BuildJobResult> FinishAsync(JobExecutionOptions executionOptions, SecurityOptions? securityOptions, CancellationToken cancellationToken)
266266
{
267267
var inputByteArrays = await Task.WhenAll(
268-
_inputs.Select(async pair => new KeyValuePair<int, ReadOnlyMemory<byte>>(pair.Key, await pair.Value.BorrowReadOnlyMemoryAsync(cancellationToken))));
268+
_inputs.Select(async pair => new KeyValuePair<int, ReadOnlyMemory<byte>>(pair.Key, await pair.Value.BorrowReadOnlyMemoryAsync(cancellationToken).ConfigureAwait(false)))).ConfigureAwait(false);
269269
using (var ctx = new JobContext())
270270
{
271271
foreach (var pair in inputByteArrays)
@@ -282,7 +282,7 @@ internal async Task<BuildJobResult> FinishAsync(JobExecutionOptions executionOpt
282282
var message = CreateJsonNodeForFramewiseWithSecurityOptions(securityOptions);
283283

284284
var response = executionOptions.OffloadCpuToThreadPool
285-
? await Task.Run(() => ctx.InvokeExecute(message), cancellationToken)
285+
? await Task.Run(() => ctx.InvokeExecute(message), cancellationToken).ConfigureAwait(false)
286286
: ctx.InvokeExecute(message);
287287

288288
// TODO: Should we handle failure before copying out the buffers??
@@ -292,7 +292,7 @@ internal async Task<BuildJobResult> FinishAsync(JobExecutionOptions executionOpt
292292
foreach (var pair in _outputs)
293293
{
294294
using var memOwner = ctx.BorrowOutputBufferMemoryAndAddReference(pair.Key);
295-
await pair.Value.AdaptiveWriteAllAsync(memOwner.Memory, cancellationToken);
295+
await pair.Value.AdaptiveWriteAllAsync(memOwner.Memory, cancellationToken).ConfigureAwait(false);
296296
}
297297
return BuildJobResult.From(response, _outputs);
298298
}
@@ -377,7 +377,7 @@ internal async Task CopyOutputsToDestinations(CancellationToken token)
377377
{
378378
using (var stream = pair.Key.ReadFromBeginning())
379379
{
380-
await pair.Value.CopyFromStreamAsyncInternal(stream, token);
380+
await pair.Value.CopyFromStreamAsyncInternal(stream, token).ConfigureAwait(false);
381381
}
382382
}
383383
}
@@ -404,15 +404,15 @@ private async Task<SubprocessFilesystemJob> PrepareForSubprocessAsync(Cancellati
404404

405405
var inputFiles = (await Task.WhenAll(_inputs.Select(async pair =>
406406
{
407-
var bytes = await pair.Value.BorrowReadOnlyMemoryAsync(cancellationToken);
407+
var bytes = await pair.Value.BorrowReadOnlyMemoryAsync(cancellationToken).ConfigureAwait(false);
408408

409409
var file = job.Provider.Create(cleanupFiles, bytes.Length);
410410
job.Cleanup.Add(file);
411411
return (io_id: pair.Key, direction: "in",
412412
io: new JsonObject { { "file", file.Path } },
413413
bytes, bytes.Length, File: file);
414414

415-
}))).ToArray();
415+
})).ConfigureAwait(false)).ToArray();
416416

417417
var outputCapacity = outputBufferCapacity ?? inputFiles.Max(v => v.Length) * 2;
418418
var outputFiles = _outputs.Select(pair =>
@@ -427,7 +427,7 @@ private async Task<SubprocessFilesystemJob> PrepareForSubprocessAsync(Cancellati
427427
foreach (var f in inputFiles)
428428
{
429429
using var accessor = f.File.WriteFromBeginning();
430-
await accessor.WriteMemoryAsync(f.bytes, cancellationToken);
430+
await accessor.WriteMemoryAsync(f.bytes, cancellationToken).ConfigureAwait(false);
431431
}
432432

433433
// job.JobMessage = new
@@ -505,7 +505,7 @@ internal async Task<BuildJobResult> FinishInSubprocessAsync(SecurityOptions? sec
505505
throw new FileNotFoundException("Cannot find imageflow_tool using path \"" + imageflowToolPath + "\" and currect folder \"" + Directory.GetCurrentDirectory() + "\"");
506506
}
507507

508-
using (var job = await PrepareForSubprocessAsync(cancellationToken, securityOptions, true, outputBufferCapacity))
508+
using (var job = await PrepareForSubprocessAsync(cancellationToken, securityOptions, true, outputBufferCapacity).ConfigureAwait(false))
509509
{
510510

511511
var startInfo = new ProcessStartInfo
@@ -517,7 +517,7 @@ internal async Task<BuildJobResult> FinishInSubprocessAsync(SecurityOptions? sec
517517
FileName = imageflowToolPath
518518
};
519519

520-
var results = await ProcessEx.RunAsync(startInfo, cancellationToken);
520+
var results = await ProcessEx.RunAsync(startInfo, cancellationToken).ConfigureAwait(false);
521521

522522
var output = results.GetBufferedOutputStream();
523523
var errors = results.GetStandardErrorString();
@@ -535,7 +535,7 @@ internal async Task<BuildJobResult> FinishInSubprocessAsync(SecurityOptions? sec
535535
}
536536
}
537537

538-
await job.CopyOutputsToDestinations(cancellationToken);
538+
await job.CopyOutputsToDestinations(cancellationToken).ConfigureAwait(false);
539539

540540
var outputMemory = output.GetWrittenMemory();
541541
return BuildJobResult.From(new MemoryJsonResponse(results.ExitCode, outputMemory), _outputs);
@@ -544,7 +544,7 @@ internal async Task<BuildJobResult> FinishInSubprocessAsync(SecurityOptions? sec
544544

545545
internal async Task<IPreparedFilesystemJob> WriteJsonJobAndInputs(CancellationToken cancellationToken, SecurityOptions? securityOptions, bool deleteFilesOnDispose)
546546
{
547-
return await PrepareForSubprocessAsync(cancellationToken, securityOptions, deleteFilesOnDispose);
547+
return await PrepareForSubprocessAsync(cancellationToken, securityOptions, deleteFilesOnDispose).ConfigureAwait(false);
548548
}
549549

550550
private readonly List<BuildItemBase> _nodesCreated = new List<BuildItemBase>(10);
@@ -598,10 +598,10 @@ private static IEnumerable<Tuple<long, long, EdgeKind>> CollectEdges(ICollection
598598
internal JsonNode ToFramewise()
599599
{
600600
var nodes = CollectUnique();
601-
return ToFramewiseGraph(nodes);
601+
return ImageJob.ToFramewiseGraph(nodes);
602602
}
603603

604-
private JsonNode ToFramewiseGraph(ICollection<BuildItemBase> uniqueNodes)
604+
private static JsonNode ToFramewiseGraph(ICollection<BuildItemBase> uniqueNodes)
605605
{
606606
var lowestUid = LowestUid(uniqueNodes) ?? 0;
607607
var edges = CollectEdges(uniqueNodes)
@@ -707,7 +707,7 @@ public static async Task<ImageInfo> GetImageInfo(IBytesSource image, Cancellatio
707707
{
708708
try
709709
{
710-
var inputByteArray = await image.GetBytesAsync(cancellationToken);
710+
var inputByteArray = await image.GetBytesAsync(cancellationToken).ConfigureAwait(false);
711711
using (var ctx = new JobContext())
712712
{
713713
ctx.AddInputBytesPinned(0, inputByteArray);
@@ -758,7 +758,7 @@ public static async ValueTask<ImageInfo> GetImageInfoAsync(IAsyncMemorySource im
758758
{
759759
try
760760
{
761-
var inputMemory = await image.BorrowReadOnlyMemoryAsync(cancellationToken);
761+
var inputMemory = await image.BorrowReadOnlyMemoryAsync(cancellationToken).ConfigureAwait(false);
762762
if (inputMemory.Length == 0)
763763
{
764764
throw new ArgumentException("Input image is empty");
@@ -782,7 +782,7 @@ public static async ValueTask<ImageInfo> GetImageInfoAsync(IAsyncMemorySource im
782782
}
783783
}
784784
/// <summary>
785-
/// Returns true if it is likely that Imageflow can decode the given image based on the first 12 bytes of the file.
785+
/// Returns true if it is likely that Imageflow can decode the given image based on the first 12 bytes of the file.
786786
/// </summary>
787787
/// <param name="first12Bytes">The first 12 or more bytes of the file</param>
788788
/// <returns></returns>
@@ -795,7 +795,7 @@ public static bool CanDecodeBytes(byte[] first12Bytes)
795795
/// <summary>
796796
/// Returns a MIME type string such as "image/jpeg" based on the provided first 12 bytes of the file.
797797
/// Only guaranteed to work for image types Imageflow supports, but support for more file types may be added
798-
/// later.
798+
/// later.
799799
/// </summary>
800800
/// <param name="first12Bytes">The first 12 or more bytes of the file</param>
801801
/// <returns></returns>

src/Imageflow/Fluent/JobExecutionOptions.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -2,5 +2,5 @@ namespace Imageflow.Fluent;
22

33
internal class JobExecutionOptions
44
{
5-
internal bool OffloadCpuToThreadPool { get; set; } = false;
5+
internal bool OffloadCpuToThreadPool { get; set; }
66
}

src/Imageflow/Fluent/MemorySource.cs

+3-3
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ public sealed class MemorySource : IAsyncMemorySource, IMemorySource
1111

1212
public static IAsyncMemorySource TakeOwnership(IMemoryOwner<byte> ownedMemory, MemoryLifetimePromise promise)
1313
{
14-
ArgumentNullThrowHelper.ThrowIfNull(ownedMemory);
14+
Argument.ThrowIfNull(ownedMemory);
1515
if (promise != MemoryLifetimePromise.MemoryOwnerDisposedByMemorySource)
1616
{
1717
throw new ArgumentException(
@@ -26,7 +26,7 @@ private MemorySource(ReadOnlyMemory<byte>? borrowedMemory, IMemoryOwner<byte>? o
2626
{
2727
if (promise == MemoryLifetimePromise.MemoryOwnerDisposedByMemorySource)
2828
{
29-
ArgumentNullThrowHelper.ThrowIfNull(ownedMemory);
29+
Argument.ThrowIfNull(ownedMemory);
3030
if (borrowedMemory.HasValue)
3131
{
3232
throw new ArgumentException(
@@ -39,7 +39,7 @@ private MemorySource(ReadOnlyMemory<byte>? borrowedMemory, IMemoryOwner<byte>? o
3939
throw new ArgumentNullException(nameof(borrowedMemory));
4040
}
4141

42-
ArgumentNullThrowHelper.ThrowIfNull(borrowedMemory);
42+
Argument.ThrowIfNull(borrowedMemory);
4343
_borrowedMemory = borrowedMemory;
4444
_ownedMemory = ownedMemory;
4545
}

src/Imageflow/Fluent/PerformanceDetails.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ public string GetFirstFrameSummary()
4343
foreach (var n in Frames.First().Nodes)
4444
{
4545
sb.Append(n.Name);
46-
sb.Append("(");
46+
sb.Append('(');
4747
sb.Append((n.WallMicroseconds / 1000.0).ToString("0.####"));
4848
sb.Append("ms) ");
4949
}

src/Imageflow/Fluent/StreamSource.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ public async Task<ArraySegment<byte>> GetBytesAsync(CancellationToken cancellati
5151
if (_copy == null)
5252
{
5353
_copy = new RecyclableMemoryStream(Mgr, "StreamSource: IBytesSource", length);
54-
await underlying.CopyToAsync(_copy, 81920, cancellationToken);
54+
await underlying.CopyToAsync(_copy, 81920, cancellationToken).ConfigureAwait(false);
5555
}
5656

5757
return new ArraySegment<byte>(_copy.GetBuffer(), 0,

src/Imageflow/IO/ProcessEx.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,7 @@ public static async Task<ProcessResults> RunAsync(ProcessStartInfo processStartI
131131
process.BeginOutputReadLine();
132132
process.BeginErrorReadLine();
133133

134-
return await tcs.Task;
134+
return await tcs.Task.ConfigureAwait(false);
135135
}
136136
}
137137
}

src/Imageflow/Internal.Helpers/ArgumentNullThrowHelperPolyfill.cs

+3-3
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ namespace Imageflow.Internal.Helpers;
77
// The .NET Foundation licenses this file to you under the MIT license.
88
// Imazen licenses any changes to th
99

10-
internal static partial class ArgumentNullThrowHelper
10+
internal static class Argument
1111
{
1212
/// <summary>Throws an <see cref="ArgumentNullException"/> if <paramref name="argument"/> is null.</summary>
1313
/// <param name="argument">The reference type argument to validate as non-null.</param>
@@ -24,7 +24,7 @@ public static void ThrowIfNull(
2424
Throw(paramName);
2525
}
2626
#else
27-
ArgumentNullException.ThrowIfNull(argument, paramName);
27+
Argument.ThrowIfNull(argument, paramName);
2828
#endif
2929
}
3030

@@ -44,7 +44,7 @@ public static void ThrowIf([DoesNotReturnIf(true)] bool condition, object instan
4444
#if NET8_0_OR_GREATER
4545

4646
ObjectDisposedException.ThrowIf(condition, instance);
47-
#else
47+
#else
4848
if (condition)
4949
{
5050
throw new ObjectDisposedException(instance?.GetType().Name);

0 commit comments

Comments
 (0)