Allow returning a result from Progress.StartAsync/Status.StartAsync

This commit is contained in:
Thomas Freudenberg 2021-01-06 08:08:38 +01:00 committed by GitHub
parent 0796bad598
commit 8901450283
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 54 additions and 4 deletions

View File

@ -80,9 +80,31 @@ namespace Spectre.Console
throw new ArgumentNullException(nameof(action));
}
_ = await StartAsync<object?>(async progressContext =>
{
await action(progressContext);
return default;
});
}
/// <summary>
/// Starts the progress task list.
/// </summary>
/// <param name="action">The action to execute.</param>
/// <typeparam name="T">The result type of task.</typeparam>
/// <returns>A <see cref="Task{T}"/> representing the asynchronous operation.</returns>
public async Task<T> StartAsync<T>(Func<ProgressContext, Task<T>> action)
{
if (action is null)
{
throw new ArgumentNullException(nameof(action));
}
var renderer = CreateRenderer();
renderer.Started();
T result;
try
{
using (new RenderHookScope(_console, renderer))
@ -93,12 +115,12 @@ namespace Spectre.Console
{
using (var thread = new ProgressRefreshThread(context, renderer.RefreshRate))
{
await action(context).ConfigureAwait(false);
result = await action(context).ConfigureAwait(false);
}
}
else
{
await action(context).ConfigureAwait(false);
result = await action(context).ConfigureAwait(false);
}
context.Refresh();
@ -108,6 +130,8 @@ namespace Spectre.Console
{
renderer.Completed(AutoClear);
}
return result;
}
private ProgressRenderer CreateRenderer()

View File

@ -60,6 +60,32 @@ namespace Spectre.Console
/// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
public async Task StartAsync(string status, Func<StatusContext, Task> action)
{
if (action is null)
{
throw new ArgumentNullException(nameof(action));
}
_ = await StartAsync<object?>(status, async statusContext =>
{
await action(statusContext);
return default;
});
}
/// <summary>
/// Starts a new status display.
/// </summary>
/// <param name="status">The status to display.</param>
/// <param name="action">he action to execute.</param>
/// <typeparam name="T">The result type of task.</typeparam>
/// <returns>A <see cref="Task{T}"/> representing the asynchronous operation.</returns>
public async Task<T> StartAsync<T>(string status, Func<StatusContext, Task<T>> action)
{
if (action is null)
{
throw new ArgumentNullException(nameof(action));
}
// Set the progress columns
var spinnerColumn = new SpinnerColumn(Spinner ?? Spinner.Known.Default)
{
@ -79,10 +105,10 @@ namespace Spectre.Console
new TaskDescriptionColumn(),
});
await progress.StartAsync(async ctx =>
return await progress.StartAsync(async ctx =>
{
var statusContext = new StatusContext(ctx, ctx.AddTask(status), spinnerColumn);
await action(statusContext).ConfigureAwait(false);
return await action(statusContext).ConfigureAwait(false);
}).ConfigureAwait(false);
}
}