Cancellazione Task

This commit is contained in:
Maddo 2017-10-05 14:16:43 +02:00
commit d2ab7bfce6
5 changed files with 188 additions and 46 deletions

View file

@ -394,7 +394,7 @@ namespace CatalogLib
}
switch (_picSettings.Posizione.ToUpper())
switch (_picSettings.TextPosition.ToString().ToUpper())
{
case "ALTO":
yPosFromBottom1 = _picSettings.Margine;

View file

@ -23,7 +23,16 @@ namespace CatalogLib
{
public class ImgSharpCreator : IImageProcessor
{
private Image<Rgba32> _logo;
public ImgSharpCreator()
{
if (!PicSettings.Instance.EnableLogo) return;
if (string.IsNullOrWhiteSpace(PicSettings.Instance.LogoPath)) return;
if (!File.Exists(PicSettings.Instance.LogoPath)) return;
_logo = Image.Load(PicSettings.Instance.LogoPath);
}
private FileInfo _currentFile;
public void Start(FileInfo workFile)
{
@ -141,7 +150,7 @@ namespace CatalogLib
//var fff = FontCollection.SystemFonts.Find(PicSettings.Instance.NomeFont);
//var font = new Font(fff, (float)PicSettings.Instance.DimensioneFont, FontStyle.Regular);
//image.DrawText("sssssssssssssssssssssssssssssssssssssssssssssss", font, Color.Black, new Vector2(200, 200));
image.Save(Path.Combine(PicSettings.Instance.DirectoryDestinazione, workFile.Name), new JpegEncoder(){Quality = PicSettings.Instance.CompressioneJpeg});
image.Save(Path.Combine(PicSettings.Instance.DirectoryDestinazione, workFile.Name), new JpegEncoder() { Quality = PicSettings.Instance.CompressioneJpeg });
//image.Resize(200, 200).Save("");
MaddoLogger.Log("Saved Image: {0} to: {1}", workFile.FullName, Path.Combine(PicSettings.Instance.DirectoryDestinazione, workFile.Name));
@ -201,7 +210,7 @@ namespace CatalogLib
throw new ArgumentOutOfRangeException();
}
// todo calcolare ridimensionamento
var size = new Vector2();
var size = new Size();
if (PicSettings.Instance.FotoMantieniDimensioni)
{
@ -213,15 +222,15 @@ namespace CatalogLib
if (image.Width > image.Height)
{
// larghezza è il lato lungo
size = GetResizeDimensions(new Vector2(image.Width, image.Height),
new Vector2(PicSettings.Instance.FotoLarghezza, PicSettings.Instance.FotoAltezza),
size = GetResizeDimensions(new Size(image.Width, image.Height),
new Size(PicSettings.Instance.FotoLarghezza, PicSettings.Instance.FotoAltezza),
true);
}
else
{
// altezza è il lato lungo
size = GetResizeDimensions(new Vector2(image.Width, image.Height),
new Vector2(PicSettings.Instance.FotoLarghezza, PicSettings.Instance.FotoAltezza),
size = GetResizeDimensions(new Size(image.Width, image.Height),
new Size(PicSettings.Instance.FotoLarghezza, PicSettings.Instance.FotoAltezza),
false);
}
break;
@ -229,24 +238,24 @@ namespace CatalogLib
if (image.Width > image.Height)
{
// larghezza è il lato lungo
size = GetResizeDimensions(new Vector2(image.Width, image.Height),
new Vector2(PicSettings.Instance.FotoLarghezza, PicSettings.Instance.FotoAltezza),
size = GetResizeDimensions(new Size(image.Width, image.Height),
new Size(PicSettings.Instance.FotoLarghezza, PicSettings.Instance.FotoAltezza),
false);
}
else
{
// altezza è il lato lungo
size = GetResizeDimensions(new Vector2(image.Width, image.Height),
new Vector2(PicSettings.Instance.FotoLarghezza, PicSettings.Instance.FotoAltezza),
size = GetResizeDimensions(new Size(image.Width, image.Height),
new Size(PicSettings.Instance.FotoLarghezza, PicSettings.Instance.FotoAltezza),
true);
}
break;
default:
throw new ArgumentOutOfRangeException();
}
image.Mutate(x => x.Resize((int)Math.Round(size.X), (int)Math.Round(size.Y), resampler));
image.Mutate(x => x.Resize((size.Width), (size.Height), resampler));
//Width Formula:
//original height / original width * new width = new height
@ -261,15 +270,15 @@ namespace CatalogLib
}
private Vector2 GetResizeDimensions(Vector2 originalSize, Vector2 newSize, bool isWidth)
private Size GetResizeDimensions(Size originalSize, Size newSize, bool isWidth)
{
if (isWidth)
{
return new Vector2(newSize.X, originalSize.Y / originalSize.X * newSize.X);
return new Size(newSize.Width, originalSize.Height / originalSize.Width * newSize.Height);
}
else
{
return new Vector2(originalSize.X / originalSize.Y * newSize.Y, newSize.Y);
return new Size(originalSize.Width / originalSize.Height * newSize.Height, newSize.Height);
}
}
@ -464,6 +473,49 @@ namespace CatalogLib
}
private void AddLogo(Image<Rgba32> image)
{
//if (string.IsNullOrWhiteSpace(PicSettings.Instance.LogoPath)) return;
//if (!File.Exists(PicSettings.Instance.LogoPath)) return;
//using (Image<Rgba32> logo = Image.Load(PicSettings.Instance.LogoPath))
//{
// Size size = new Size();
// Point location = new Point();
// image.Mutate(x => x.DrawImage(logo, size, location, new GraphicsOptions()
// {
// }));
//}
if (_logo != null)
{
var width = PicSettings.Instance.LogoWidth;
var height = PicSettings.Instance.LogoHeight;
var fattoreAlt = _logo.Height / height;
var fattoreLarg = _logo.Width / width;
var nuovaSize = new Size();
nuovaSize = GetResizeDimensions(new Size(_logo.Width, _logo.Height), new Size(width, height), fattoreLarg > fattoreAlt);
//todo riguardare perché non torna cosa ho fatto
int margineUsato;
int margineL;
bool inPercentualeL;
inPercentualeL = PicSettings.Instance.LogoMargin.EndsWith("%");
if (inPercentualeL)
{ margineL = int.Parse(PicSettings.Instance.LogoMargin.Replace("%", ""));}
else
{
margineL = int.Parse(PicSettings.Instance.LogoMargin);
}
}
}
private void WriteTextFixed(Image<Rgba32> image)
{
var fo = SixLabors.Fonts.SystemFonts.Find("Microsoft Sans Serif");

View file

@ -151,10 +151,10 @@ namespace CatalogLib
float fl = 0;
SetFloat(key, float.TryParse(_settingsDict[key].ToString(), out f) ? fl : defaultValue);
return (float) _settingsDict[key];
return (float)_settingsDict[key];
}
public T Get<T>(string key, T defaultValue)
{
@ -220,8 +220,8 @@ namespace CatalogLib
public bool DirAggiornaSottoDirectory
{
get { return this.GetBool("DirAggiornaSottoDirectory", true); }
set { this.SetBool("DirAggiornaSottoDirectory", value); }
get => this.GetBool("DirAggiornaSottoDirectory", true);
set => this.SetBool("DirAggiornaSottoDirectory", value);
}
public bool Grassetto
@ -313,7 +313,9 @@ namespace CatalogLib
set { SetString("DirDestinazione", value); }
}
public int Margine { get => GetInt("Margin", 1);
public int Margine
{
get => GetInt("Margin", 1);
set => SetInt("Margin", value);
}
public float MargVert { get; set; }
@ -493,19 +495,35 @@ namespace CatalogLib
set => SetString("ResizeDimension", value.ToString());
}
[Obsolete]
public string Posizione
public string LogoPath
{
get => string.Empty;
set { }
get => GetString("LogoPath");
set => SetString("LogoPath", value);
}
public int LogoWidth
{
get => GetInt("LogoWidth");
set => SetInt("LogoWidth", value);
}
public int LogoHeight
{
get => GetInt("LogoHeight");
set => SetInt("LogoHeight", value);
}
public string LogoMargin
{
get => GetString("LogoMargin");
set => SetString("LogoMargin", value);
}
#endregion
#region Enums
#endregion
}

View file

@ -24,7 +24,7 @@
<Setter Property="Margin" Value="2,2,5,5" />
</Style>
<Style TargetType="ComboBox" BasedOn="{StaticResource CommonStyle}"></Style>
</Window.Resources>
<Grid>
<DockPanel LastChildFill="True">
@ -67,7 +67,7 @@
</StackPanel>
</TabItem.Header>
<controls:TextSettingsControl></controls:TextSettingsControl>
</TabItem>
<TabItem>
<TabItem.Header>
@ -182,15 +182,15 @@
<GroupBox DockPanel.Dock="Right" Header="Statistiche">
<StackPanel Orientation="Vertical">
<StackPanel Orientation="Horizontal">
<Button Content="Carica Impostazioni" Command="{Binding ImportSettingsCommand}" Style="{DynamicResource SquareButtonStyle}"></Button>
<Button Content="Salva Impostazioni" Command="{Binding ExportSettingsCommand}" Style="{DynamicResource SquareButtonStyle}"></Button>
<Button Content="Carica Impostazioni" Command="{Binding ImportSettingsCommand}" Style="{DynamicResource SquareButtonStyle}" IsEnabled="{Binding IsUiActive}"></Button>
<Button Content="Salva Impostazioni" Command="{Binding ExportSettingsCommand}" Style="{DynamicResource SquareButtonStyle}" IsEnabled="{Binding IsUiActive}"></Button>
</StackPanel>
<Button Content="Start" Command="{Binding StartCommand}" Style="{DynamicResource AccentedSquareButtonStyle}"></Button>
<Button Content="Start" Command="{Binding StartCommand}" Style="{DynamicResource AccentedSquareButtonStyle}" IsEnabled="{Binding IsUiActive}"></Button>
<Button Content="STOP" Command="{Binding StopCommand}" Style="{DynamicResource SquareButtonStyle}"/>
<TextBlock Text="{Binding CurrentImage}"></TextBlock>
<TextBlock Text="{Binding TotalPictures}"></TextBlock>
</StackPanel>
</GroupBox>
</StackPanel>

View file

@ -1,9 +1,11 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using CatalogLib;
using GalaSoft.MvvmLight.Command;
@ -41,6 +43,7 @@ namespace WPFCatalog
public RelayCommand OpenDestinationFolderCommand { get; private set; }
public RelayCommand StartCommand { get; private set; }
public RelayCommand StopCommand { get; private set; }
public RelayCommand PickFontCommand { get; private set; }
@ -56,6 +59,8 @@ namespace WPFCatalog
OpenDestinationFolderCommand = new RelayCommand(OpenDestinationFolder);
StartCommand = new RelayCommand(Start);
StopCommand = new RelayCommand(Stop);
PickFontCommand = new RelayCommand(PickFont);
}
@ -84,9 +89,11 @@ namespace WPFCatalog
public bool Completed;
}
private Task _workTask;
//private List<ImageTask> _tasks;
private async void Start()
{
//Task outerTask = new Task(() =>
//{
// Stopwatch s = new Stopwatch();
@ -126,24 +133,58 @@ namespace WPFCatalog
// MaddoLogger.Log("Finished: {0}, {1}", s.Elapsed, s.ElapsedMilliseconds);
// DialogHelper.PopUpAlert($"Finished: {s.Elapsed}, {s.ElapsedMilliseconds}", "message");
//});
if (/*_workTask == null || _workTask.IsCanceled || _workTask.IsCompleted || _workTask.IsFaulted*/!_isRunning)
{
_workTask = OuterTask();
try
{
await _workTask;
}
catch (TaskCanceledException e)
{
MaddoLogger.LogError(e);
MaddoLogger.LogError("Master Task cancelled");
//throw;
}
}
Task outerTask = OuterTask();
await outerTask;
}
private void Stop()
{
if (_isRunning)
{
_tokenSource.Cancel();
}
}
private CancellationTokenSource _tokenSource;
private bool _isRunning = false;
private async Task OuterTask()
{
_isRunning = true;
_tokenSource = new CancellationTokenSource();
var token = _tokenSource.Token;
var tasks = new ConcurrentBag<Task>();
IsUiActive = false;
Stopwatch s = new Stopwatch();
var tasks = new List<Task>();
//var tasks = new List<Task>();
// todo folder mode
MaddoLogger.Log("Starting elaboration");
var files = Directory.EnumerateFiles(PicSettings.DirectorySorgente).ToArray();
TotalPictures = files.Count();
IImageProcessor i = new ImgSharpCreator();
foreach (var file in files)
{
//Task t = new Task(() =>
@ -151,8 +192,8 @@ namespace WPFCatalog
// //CompleteFile(file);
//});
var t = FileTask(file);
var t = FileTask(file, i, token);
tasks.Add(t);
//_tasks.Add(new ImageTask() { ImageName = file, TaskImage = t, Completed = false });
@ -165,24 +206,48 @@ namespace WPFCatalog
try
{
await Task.WhenAll(tasks);
}
catch (AggregateException e)
{
MaddoLogger.LogError(e);
MaddoLogger.LogError("Task cancelled");
//Console.WriteLine(e);
//Console.WriteLine("Task cancelled");
//throw;
}
finally
{
_tokenSource.Dispose();
await Task.WhenAll(tasks);
//Task.WhenAll(tasks).Start();
s.Stop();
//tt.RunSynchronously();
MaddoLogger.Log("Finished: {0}, {1}", s.Elapsed, s.ElapsedMilliseconds);
DialogHelper.PopUpAlert($"Finished: {s.Elapsed}, {s.ElapsedMilliseconds}", "message");
IsUiActive = true;
_isRunning = false;
}
//Task.WhenAll(tasks).Start();
s.Stop();
//tt.RunSynchronously();
MaddoLogger.Log("Finished: {0}, {1}", s.Elapsed, s.ElapsedMilliseconds);
DialogHelper.PopUpAlert($"Finished: {s.Elapsed}, {s.ElapsedMilliseconds}", "message");
}
private async Task FileTask(string file)
private async Task FileTask(string file, IImageProcessor i, CancellationToken token)
{
if (token.IsCancellationRequested == true)
{
token.ThrowIfCancellationRequested();
}
MaddoLogger.Log("Starting task for image {0}", file);
IImageProcessor i = new ImgSharpCreator();
await Task.Run(() => i.Start(new FileInfo(file)));
//IImageProcessor i = new ImgSharpCreator();
await Task.Run(() => i.Start(new FileInfo(file)), token);
CurrentImage = file;
TotalPictures--;
}
@ -265,6 +330,13 @@ namespace WPFCatalog
#region Proprietà
private bool _isUiActive = true;
public bool IsUiActive
{
get => _isUiActive;
set { _isUiActive = value; RaisePropertyChanged("IsUiActive"); }
}
private string _currentImage;
public string CurrentImage