Properly implement cancellation

This commit is contained in:
Dean Herbert 2019-06-10 13:37:20 +09:00
parent b4d2d0bd0b
commit 2d1a54e634
1 changed files with 15 additions and 6 deletions

View File

@ -154,6 +154,9 @@ protected async Task Import(ProgressNotification notification, params string[] p
await Task.WhenAll(paths.Select(path => Import(path, notification.CancellationToken).ContinueWith(t =>
{
if (notification.CancellationToken.IsCancellationRequested)
return;
lock (notification)
{
current++;
@ -172,7 +175,7 @@ await Task.WhenAll(paths.Select(path => Import(path, notification.CancellationTo
var e = t.Exception.InnerException ?? t.Exception;
Logger.Error(e, $@"Could not import ({Path.GetFileName(path)})");
}
})));
}, TaskContinuationOptions.NotOnCanceled)));
if (imported.Count == 0)
{
@ -207,6 +210,8 @@ await Task.WhenAll(paths.Select(path => Import(path, notification.CancellationTo
/// <returns>The imported model, if successful.</returns>
public async Task<TModel> Import(string path, CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
TModel import;
using (ArchiveReader reader = getReaderFrom(path))
import = await Import(reader, cancellationToken);
@ -240,6 +245,8 @@ public async Task<TModel> Import(string path, CancellationToken cancellationToke
/// <param name="cancellationToken">An optional cancellation token.</param>
public async Task<TModel> Import(ArchiveReader archive, CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
try
{
var model = CreateModel(archive);
@ -250,6 +257,10 @@ public async Task<TModel> Import(ArchiveReader archive, CancellationToken cancel
return await Import(model, archive, cancellationToken);
}
catch (TaskCanceledException)
{
throw;
}
catch (Exception e)
{
Logger.Error(e, $"Model creation of {archive.Name} failed.", LoggingTarget.Database);
@ -286,6 +297,8 @@ private string computeHash(ArchiveReader reader)
/// <param name="cancellationToken">An optional cancellation token.</param>
public async Task<TModel> Import(TModel item, ArchiveReader archive = null, CancellationToken cancellationToken = default) => await Task.Factory.StartNew(async () =>
{
cancellationToken.ThrowIfCancellationRequested();
delayEvents();
try
@ -301,10 +314,6 @@ public async Task<TModel> Import(TModel item, ArchiveReader archive = null, Canc
{
await Populate(item, archive, cancellationToken);
}
catch (TaskCanceledException)
{
return item = null;
}
finally
{
if (!Delete(localItem))
@ -364,7 +373,7 @@ public async Task<TModel> Import(TModel item, ArchiveReader archive = null, Canc
}
return item;
}, CancellationToken.None, TaskCreationOptions.HideScheduler, IMPORT_SCHEDULER).Unwrap();
}, cancellationToken, TaskCreationOptions.HideScheduler, IMPORT_SCHEDULER).Unwrap();
/// <summary>
/// Perform an update of the specified item.