带取消的WriteLineAsync

时间:2016-02-14 18:10:48

标签: c#

我将我的方法扩展到async,但我希望有可能通过用户请求和超时时间取消,但WriteLineAsync不支持取消令牌的切换。我尝试了嵌套的任务,但不起作用。有人可以支持我吗?

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;
}

1 个答案:

答案 0 :(得分:0)

到目前为止,至少,您无法取消WriteLineAsync本身。

您可以做的最好是在操作之间取消:

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);
}

为了清晰和灵活,我可能将其分解为:

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);
}