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

@ -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