gpt4 book ai didi

c# - WriteLineAsync 与取消

转载 作者:行者123 更新时间:2023-11-30 18:21:29 27 4
gpt4 key购买 nike

我将我的方法扩展到 async,但我希望可以通过用户请求和超时时间取消,但 WriteLineAsync 不支持取消 token 的移交。我尝试了嵌套任务,但没有用。有人可以支持我吗?

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

最佳答案

至少到目前为止,您无法取消 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);
}

关于c# - WriteLineAsync 与取消,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35395275/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com