要创建异步等待文件 [英] Async wait for file to be created

查看:122
本文介绍了要创建异步等待文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么将是最干净的方式等待为通过外部应用程序创建的文件?

 异步任务doSomethingWithFile(字符串文件路径)
    {
        // 1.指日可待路径存在
        // 2.请与文件的东西
    }


解决方案

所以第一个关键点是,你可以使用 FileSystemWatcher的被通知当一个文件系统事件在一个特定的路径的改变。如果,例如,希望得到通知时,在特定位置创建一个文件,你可以了解一下。

接下来,我们可以创建一个使用方法 TaskCompletionSource 当文件系统观察触发有关事件触发任务的完成。

 公共静态任务WhenFileCreated(字符串路径)
{
    如果(File.Exists(路径))
        返回Task.FromResult(真);    VAR TCS =新TaskCompletionSource<布尔>();
    FileSystemWatcher的守望者=新FileSystemWatcher的(Path.GetDirectoryName(路径));    FileSystemEventHandler createdHandler = NULL;
    RenamedEventHandler renamedHandler = NULL;
    createdHandler =(S,E)=>
    {
        如果(e.Name == Path.GetFileName(路径))
        {
            tcs.TrySetResult(真);
            watcher.Created - = createdHandler;
            watcher.Dispose();
        }
    };    renamedHandler =(S,E)=>
    {
        如果(e.Name == Path.GetFileName(路径))
        {
            tcs.TrySetResult(真);
            watcher.Renamed - = renamedHandler;
            watcher.Dispose();
        }
    };    watcher.Created + = createdHandler;
    watcher.Renamed + = renamedHandler;    watcher.EnableRaisingEvents = TRUE;    返回tcs.Task;
}

请注意,如果这首先检查该文件存在,允许它立即如果适用的退出。它也同时使用创建的,并更名为处理任一选项,可以让该文件在未来的某一时刻存在。在 FileSystemWatcher的也只是看目录,所以要得到指定路径的目录,然后检查每个受影响的文件的文件名在事件处理程序是很重要的。

另外请注意,code时,它的完成消除了事件处理程序。

这使我们可以写:

 公共静态异步任务美孚()
{
    等待WhenFileCreated(@C:\\ TEMP \\ test.txt的);
    Console.WriteLine(这是aliiiiiive !!!);
}

What would be the cleanest way to await for a file to be created by an external application?

    async Task doSomethingWithFile(string filepath)
    {
        // 1. await for path exists
        // 2. Do something with file
    }

解决方案

So the first key point is that you can use a FileSystemWatcher to be notified when a file system event changes at a particular path. If you, for example, want to be notified when a file is created at a particular location you can find out.

Next, we can create a method that uses a TaskCompletionSource to trigger the completion of a task when the file system watcher triggers the relevant event.

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

Note that this first checks if the file exists, to allow it to exit right away if applicable. It also uses both the created and renamed handlers as either option could allow the file to exist at some point in the future. The FileSystemWatcher also only watches directories, so it's important to get the directory of the specified path and then check the filename of each affected file in the event handler.

Also note that the code removes the event handlers when it's done.

This allows us to write:

public static async Task Foo()
{
    await WhenFileCreated(@"C:\Temp\test.txt");
    Console.WriteLine("It's aliiiiiive!!!");
}

这篇关于要创建异步等待文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆