Harici bir uygulama tarafından oluşturulacak bir dosya için await
'un en temiz yolu hangisi olurdu?Async dosya oluşturulmasını bekliyor
await Task.Run(() => {while(!File.Exists(@"yourpath.extension")){} return;});
//do all the processing
Ayrıca bir yönteme içine paket olabilir:
public static Task WaitForFileAsync(string path)
{
if (File.Exists(path)) return Task.FromResult<object>(null);
var tcs = new TaskCompletionSource<object>();
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;
}
ve sonra sadece bu gibi kullanabilirsiniz:
async Task doSomethingWithFile(string filepath)
{
// 1. await for path exists
// 2. Do something with file
}
Yol zaten mevcutsa WhenFileCreated tamamlanacak mı? –
@AlexS Hayır. Yalnızca bir satır kodla bu durumu işlemek için yöntemin başlangıcında bunu kontrol edebilirsiniz. – Servy
Dosya adı düzenlenmişse ne olur? Ayrıca, belirli bir dosya adı için beklemek istiyor. –