gpt4 book ai didi

c# - 异步任务超时

转载 作者:行者123 更新时间:2023-12-04 16:02:39 25 4
gpt4 key购买 nike

我的应用程序当前使用一些命令执行 Adob​​e Illustrator。当结果文件出现在某个确切的文件夹(具有异步功能)中时等待,并在文件准备好时对其进行处理。

但问题是,有时 Adob​​e Illustrator 会失败并且应用程序一直在等待。在这种情况下,我不知道如何应用超时机制来终止 Adob​​e Illustrator 并跳过当前进程。

这是代码:

...
await WhenFileCreated(result_file_name);
if (File.Exists(result_file_name))
{
...


public static Task WhenFileCreated(string path)
{
if (File.Exists(path))
return Task.FromResult(true);

var tcs = new TaskCompletionSource<bool>();
FileSystemWatcher watcher = new FileSystemWatcher(Path.GetDirectoryName(path));

FileSystemEventHandler createdHandler = null;
RenamedEventHandler renamedHandler = null;
createdHandler = (s, e) =>
{
if (e.Name == Path.GetFileName(path))
{
tcs.TrySetResult(true);
watcher.Created -= createdHandler;
watcher.Dispose();
}
};

renamedHandler = (s, e) =>
{
if (e.Name == Path.GetFileName(path))
{
tcs.TrySetResult(true);
watcher.Renamed -= renamedHandler;
watcher.Dispose();
}
};

watcher.Created += createdHandler;
watcher.Renamed += renamedHandler;

watcher.EnableRaisingEvents = true;

return tcs.Task;
}

如何对此应用超时?有什么建议?

最佳答案

最简单的方法是与 Task.Delay 比赛。针对实际任务:

await Task.WhenAny(WhenFileCreated(result_file_name), 
Task.Delay(TimeSpan.FromSeconds(5));

更好的方法是在异步方法中实现取消
public static Task WhenFileCreated(string path, 
CancellationToken ct =
default(CancellationToken))
{
//...
var tcs = new TaskCompletionSource<bool>();
ct.Register(() => tcs.TrySetCanceled())
//...
}

...然后传入 cancellation token with a timeout :
using(var cts = new CancellationTokenSource(5000))
{
try
{
await WhenFileCreated(string path, cts.Token);
}
catch(TaskCanceledException)
{
//...
}
}

关于c# - 异步任务超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50042445/

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