Async wait for file to be created

后端 未结 4 1004
别那么骄傲
别那么骄傲 2020-12-10 04:05

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

    async Task doSomethingWithFile(string filepath)         


        
4条回答
  •  庸人自扰
    2020-12-10 04:31

    This is how I'd do it:

    await Task.Run(() => {while(!File.Exists(@"yourpath.extension")){} return;});
    //do all the processing
    

    You could also package it into a method:

    public static Task WaitForFileAsync(string path)
    {
        if (File.Exists(path)) return Task.FromResult(null);
        var tcs = new TaskCompletionSource();
        FileSystemWatcher watcher = new FileSystemWatcher(Path.GetDirectoryName(path));
        watcher.Created += (s, e) => 
        { 
            if (e.FullPath.Equals(path))
            { 
                tcs.TrySetResult(null);
                if (watcher != null)
                {
                    watcher.EnableRaisingEvents = false;
                    watcher.Dispose();
                }
            } 
        };
        watcher.Renamed += (s, e) =>
        {
            if (e.FullPath.Equals(path))
            {
                tcs.TrySetResult(null);
                if (watcher != null)
                {
                    watcher.EnableRaisingEvents = false;
                    watcher.Dispose();
                }
            }
        };
        watcher.EnableRaisingEvents = true;
        return tcs.Task;
    }
    
    
    

    and then just use it as this:

    await WaitForFileAsync("yourpath.extension");
    //do all the processing
    

    提交回复
    热议问题