naps2/NAPS2.Sdk/Images/ScannedImageSource.cs

53 lines
1.3 KiB
C#
Raw Normal View History

namespace NAPS2.Images;
2021-12-17 22:59:54 +03:00
// TODO: Add a method or something for IAsyncEnumerable, conditionally compiling for .NET 5+
2021-12-17 22:59:54 +03:00
public abstract class ScannedImageSource
{
2021-12-17 22:59:54 +03:00
public static ScannedImageSource Empty => new EmptySource();
2019-05-04 02:25:05 +03:00
public abstract Task<ProcessedImage?> Next();
2019-05-04 02:25:05 +03:00
public async Task<List<ProcessedImage>> ToList()
2021-12-17 22:59:54 +03:00
{
var list = new List<ProcessedImage>();
2021-12-17 22:59:54 +03:00
try
{
2021-12-17 22:59:54 +03:00
await ForEach(image => list.Add(image));
}
2021-12-17 22:59:54 +03:00
catch (Exception)
{
2021-12-17 22:59:54 +03:00
// TODO: If we ever allow multiple enumeration, this will need to be rethought
foreach (var image in list)
{
2021-12-17 22:59:54 +03:00
image.Dispose();
2018-12-04 04:12:20 +03:00
}
2021-12-17 22:59:54 +03:00
throw;
2018-12-04 04:12:20 +03:00
}
2021-12-17 22:59:54 +03:00
return list;
}
public async Task ForEach(Action<ProcessedImage> action)
2021-12-17 22:59:54 +03:00
{
ProcessedImage? image;
2021-12-17 22:59:54 +03:00
while ((image = await Next()) != null)
2018-12-04 04:12:20 +03:00
{
2021-12-17 22:59:54 +03:00
action(image);
}
2021-12-17 22:59:54 +03:00
}
2019-05-04 02:25:05 +03:00
public async Task ForEach(Func<ProcessedImage, Task> action)
2021-12-17 22:59:54 +03:00
{
ProcessedImage? image;
2021-12-17 22:59:54 +03:00
while ((image = await Next()) != null)
2019-05-04 02:25:05 +03:00
{
2021-12-17 22:59:54 +03:00
await action(image);
2019-05-04 02:25:05 +03:00
}
}
2021-12-17 22:59:54 +03:00
private class EmptySource : ScannedImageSource
{
public override Task<ProcessedImage?> Next() => Task.FromResult<ProcessedImage?>(null);
2021-12-17 22:59:54 +03:00
}
}