3

I extended my method to async, but i would like to have the possibilty to cancel by user request and timeout time, but WriteLineAsync doesnt support handover of cancellation token. I tried nested Tasks, but doesnt work. Somebody can support me?

public async Task tapAsync(int x, int y, int timeouttime)
{
    CancellationTokenSource cts;
    cts = new CancellationTokenSource();
    await Task.Run(async() =>
    {
       try
       {
           cts.CancelAfter(timeouttime);
           await myWriter.WriteLineAsync("input tap " + x.ToString() + " " + y.ToString());
           await myWriter.FlushAsync();
           await Task.Delay(2000);
       }
       catch (OperationCanceledException)
       {
           Console.WriteLine("canceled");
       }
    }, cts.Token);
    cts = null;
}
Let'sRefactor
  • 3,303
  • 4
  • 27
  • 43
Shazter
  • 305
  • 1
  • 4
  • 17

1 Answers1

0

As of yet, at least, you can't cancel the WriteLineAsync itself.

The best you can do is to cancel between operations:

public async Task TapAsync(int x, int y, int timeouttime)
{
    CancellationTokenSource cts;
    cts = new CancellationTokenSource();
    cts.CancelAfter(timeouttime);
    return TapAsync(x, y, source.Token);
    await myWriter.WriteLineAsync("input tap " + x.ToString() + " " + y.ToString());
    token.ThrowIfCancellationRequested();
    await myWriter.FlushAsync();
    token.ThrowIfCancellationRequested();
    await Task.Delay(2000, token);
}

For clarity and flexibility I'd probably split that out as:

public Task TapAsync(int x, int y, int timeouttime)
{
    CancellationTokenSource cts;
    cts = new CancellationTokenSource();
    cts.CancelAfter(timeouttime);
    return TapAsync(x, y, source.Token);
}

public async Task TapAsync(int x, int y, CancellationToken token)
{
    token.ThrowIfCancellationRequested();
    await myWriter.WriteLineAsync("input tap " + x.ToString() + " " + y.ToString());
    token.ThrowIfCancellationRequested();
    await myWriter.FlushAsync();
    token.ThrowIfCancellationRequested();
    await Task.Delay(2000, token);
}
Jon Hanna
  • 110,372
  • 10
  • 146
  • 251