Skip to content

Commit 39c9a8c

Browse files
Merge pull request #222 from kroymann/dan/fix-sync-load
Load source images asynchronously to prevent thread pool exhaustion
2 parents 9a03ec8 + 0160ec3 commit 39c9a8c

2 files changed

Lines changed: 21 additions & 1 deletion

File tree

src/ImageSharp.Web/FormattedImage.cs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
using System;
55
using System.IO;
66
using System.Runtime.CompilerServices;
7+
using System.Threading.Tasks;
78
using SixLabors.ImageSharp.Advanced;
89
using SixLabors.ImageSharp.Formats;
910
using SixLabors.ImageSharp.PixelFormats;
@@ -91,12 +92,31 @@ public static FormattedImage Load(Configuration configuration, Stream source)
9192
return new FormattedImage(image, format);
9293
}
9394

95+
/// <summary>
96+
/// Loads the specified source.
97+
/// </summary>
98+
/// <param name="configuration">The configuration.</param>
99+
/// <param name="source">The source.</param>
100+
/// <returns>A <see cref="Task{FormattedImage}"/> representing the asynchronous operation.</returns>
101+
public static async Task<FormattedImage> LoadAsync(Configuration configuration, Stream source)
102+
{
103+
(Image<Rgba32> image, IImageFormat format) = await ImageSharp.Image.LoadWithFormatAsync<Rgba32>(configuration, source);
104+
return new FormattedImage(image, format);
105+
}
106+
94107
/// <summary>
95108
/// Saves image to the specified destination stream.
96109
/// </summary>
97110
/// <param name="destination">The destination stream.</param>
98111
public void Save(Stream destination) => this.Image.Save(destination, this.encoder);
99112

113+
/// <summary>
114+
/// Saves image to the specified destination stream.
115+
/// </summary>
116+
/// <param name="destination">The destination stream.</param>
117+
/// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
118+
public async Task SaveAsync(Stream destination) => await this.Image.SaveAsync(destination, this.encoder);
119+
100120
/// <summary>
101121
/// Performs application-defined tasks associated with freeing, releasing, or resetting
102122
/// unmanaged resources.

src/ImageSharp.Web/Middleware/ImageSharpMiddleware.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -335,7 +335,7 @@ private async Task ProcessRequestAsync(
335335
}
336336
else
337337
{
338-
using var image = FormattedImage.Load(this.options.Configuration, inStream);
338+
using FormattedImage image = await FormattedImage.LoadAsync(this.options.Configuration, inStream);
339339

340340
image.Process(
341341
this.logger,

0 commit comments

Comments
 (0)