Closed Jaben closed 6 years ago
Can you please give me an example of the code you would like to be able to write?
@Jaben @adamabdelhamed
After further investigation, the library already supports cancellation tokens, there is nothing to change in it, in my opinion. I think this issue should be closed, and I don't think the CTRL+C combination should be handled automatically inside PowerArgs, because the application code needs to handle cancellation token in all its subsequent calls (for example, whenever calling again "someTask.Wait" or running new tasks).
This is a working example (I also tested with a login scenario):
using PowerArgs;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace PowerArgsTest
{
[ArgExceptionBehavior(ArgExceptionPolicy.StandardExceptionHandling), TabCompletion(REPL = true, HistoryToSave = 10)]
internal class Program
{
[HelpHook]
[ArgShortcut("-?")]
[ArgDescription("Shows this help")]
public bool Help { get; set; }
[ArgActionMethod]
[ArgDescription("Prints information about the application")]
public void Info()
{
Console.WriteLine("Lorem ipsum dolor sit amet");
}
[ArgActionMethod]
[ArgDescription("Wait a bit")]
public void Wait()
{
try
{
_cancellationTokenSource = new CancellationTokenSource();
var token = _cancellationTokenSource.Token;
Console.WriteLine("... waiting 5 seconds - Click CTRL+C to cancel the operation!");
Task.Run(() => Task.Delay(5000), token).Wait(token);
Console.WriteLine("... done");
}
catch (OperationCanceledException)
{
Console.WriteLine("User cancelled");
}
catch (Exception e)
{
HandleException(e);
}
}
private static CancellationTokenSource _cancellationTokenSource;
static int Main(string[] args)
{
Console.CancelKeyPress += (sender, e) =>
{
if (_cancellationTokenSource != null)
{
_cancellationTokenSource.Cancel();
_cancellationTokenSource = null;
}
e.Cancel = true;
};
try
{
Args.InvokeAction<Program>(args);
}
catch (Exception e)
{
HandleException(e);
return 1;
}
return 0;
}
private static void HandleException(Exception ex)
{
if (ex is AggregateException aex)
{
foreach (Exception exception in aex.InnerExceptions)
{
Console.WriteLine(exception.Message);
}
}
Console.WriteLine(ex.Message);
}
}
}
@RobertoPrevato Looks good to me. I ended up using a similar design.
Thank you much for your effort on this library. It's appreciated.
First of all: thanks for the great framework!
One request: Async arg actions should support cancellation tokens -- and that should be linked to the CTRL+V as well.