108 lines
3.7 KiB
C#
108 lines
3.7 KiB
C#
|
|
using System;
|
|
using System.Collections.Concurrent;
|
|
using System.Collections.Generic;
|
|
using System.Drawing;
|
|
using System.Drawing.Imaging;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
using DH.Commons.Helper;
|
|
|
|
namespace DH.Commons.Enums
|
|
{
|
|
public class ImageSaveHelper
|
|
{
|
|
public event Action<DateTime, string> OnImageSaveExceptionRaised;
|
|
|
|
//private string baseDirectory = "";
|
|
//public string BaseDirectory
|
|
//{
|
|
// get => baseDirectory;
|
|
// set
|
|
// {
|
|
// baseDirectory = value;
|
|
// if (string.IsNullOrWhiteSpace(baseDirectory) || !Path.IsPathRooted(baseDirectory))
|
|
// {
|
|
// baseDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Images");
|
|
// }
|
|
// }
|
|
//}
|
|
public bool EnableImageSave { get; set; } = true;
|
|
|
|
public ImageSaveHelper() { }
|
|
public ImageSaveHelper(bool enableImageSave = true)
|
|
{
|
|
EnableImageSave = enableImageSave;
|
|
}
|
|
|
|
|
|
object lockObj = new object();
|
|
////耗时操作从 _taskFactory分配线程
|
|
//public TaskFactory _taskFactory = new TaskFactory(TaskCreationOptions.LongRunning, TaskContinuationOptions.LongRunning);
|
|
readonly ConcurrentQueue<ImageSaveSet> _imageQueue = new ConcurrentQueue<ImageSaveSet>();
|
|
Task _saveTask = null;
|
|
readonly object _saveLock = new object();
|
|
|
|
public async void ImageSaveAsync(ImageSaveSet set)
|
|
{
|
|
if (!EnableImageSave)
|
|
return;
|
|
|
|
await Task.Run(() =>
|
|
{
|
|
_imageQueue.Enqueue(set);
|
|
|
|
lock (_saveLock)
|
|
{
|
|
if (_saveTask == null)
|
|
{
|
|
_saveTask = Task.Run(async () =>
|
|
{
|
|
try
|
|
{
|
|
while (true)
|
|
{
|
|
while (_imageQueue.Count > 0)
|
|
{
|
|
if (_imageQueue.TryDequeue(out ImageSaveSet saveSet))
|
|
{
|
|
if (!Directory.Exists(Path.GetDirectoryName(saveSet.FullName)))
|
|
{
|
|
Directory.CreateDirectory(Path.GetDirectoryName(saveSet.FullName));
|
|
}
|
|
if (saveSet.SaveImage != null)
|
|
{
|
|
saveSet.SaveImage.Save(saveSet.FullName, saveSet.ImageFormat);
|
|
saveSet.SaveImage.Dispose();
|
|
}
|
|
saveSet = null;
|
|
}
|
|
}
|
|
|
|
await Task.Delay(2000);
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
OnImageSaveExceptionRaised?.Invoke(DateTime.Now, $"图片保存异常:{ex.GetExceptionMessage()}");
|
|
}
|
|
});
|
|
}
|
|
}
|
|
});
|
|
}
|
|
}
|
|
|
|
public class ImageSaveSet
|
|
{
|
|
public string FullName { get; set; }//带后缀 全路径
|
|
|
|
public Bitmap SaveImage { get; set; }
|
|
|
|
public ImageFormat ImageFormat { get; set; } = ImageFormat.Jpeg;
|
|
}
|
|
}
|