c# - 异步任务超时

标签 c# windows timeout

我的应用程序当前使用一些命令执行 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/

相关文章:

c# - 我如何使用 LINQ 从多表连接中获取 IList<string>?

java - 重命名文件夹中的所有文件(交换由 '_' 分隔的单词/数字)

c - 转义序列\a 不起作用

java - Android 的 HttpResponse 和超时

Spring Session - 不调用 SessionDestroyedEvent

xcode - iOS 应用程序 - 设置 UIWebView 加载超时

c# - Visual Studio 编译器如何将安全属性编译为 CIL?

C# - R 界面

windows - Windows 应用程序如何使用多个进程?

c# - Common.Logging 使用 PostSharp 和 NLog 2.0