要创建异步等待文件

编程入门 行业动态 更新时间:2024-10-27 02:21:40
本文介绍了要创建异步等待文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

异步任务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!!!"); }

更多推荐

要创建异步等待文件

本文发布于:2023-11-06 17:34:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1564340.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!