如何检查文件可用性异步



我想检查启动中的所有 c# 应用程序文件是否存在。 这段代码将做到这一点:

if (!File.Exists("MyControls.dll")
{
return false;
}

文件存在是 IO 吗? 它会冻结主线程 (UI( 吗? 没有任何 File.ExistsAsync。 如何检查文件可用性异步?

我尝试了一些其他方法,但是当文件由于FileNotFoundException而不存在时,它们都会冻结应用程序

这是另一个代码示例,我创建了一堆空的txt文件进行测试:

private static async Task<bool> ReadAsync(Encoding encoding)
{
bool x = true;
for (int i = 1; i < 25729; i++)
{
string filename = " (" + i.ToString() + ").txt";
try
{
char[] result;         
// File.OpenText : if file not exist a FileNotFoundException will 
// accur and it will freeze UI 
using (StreamReader reader = File.OpenText(filename)) 
{
result = new char[reader.BaseStream.Length];
await reader.ReadAsync(result, 0, (int)reader.BaseStream.Length);
}
}
catch (Exception ex)
{
x = false;
}        
}        
return x;
}

当文件不存在时,它会冻结 UI,但当它们存在时,它会减慢 UI 的速度,而不是完全冻结。

这种方法对于检查文件可用性是否正确,您不能帮我怎么做?

更新 1 :

我有这个功能:

private bool ISNeededFilesAvailable()
{     
if(!File.Exist("MyCustomeControls.dll"))
return false
if(!File.Exist("PARSGREEN.dll"))
return false
.
.
.
return true
}

我不确定何时何地使用此方法! 但我在一个名为 startupWindow 的窗口的加载事件中使用它,并在主窗口打开之前调用 showdialog((:

private void StartupWindow_Loaded(object sender, RoutedEventArgs e)
{
if (!ISNeededFilesAvailable())
Application.close();
else
this.close();
}

public MainWindow()
{
StartupWindow sw = new StartupWindow ()
sw.showdialog();
InitializeComponent();
}

只需将函数包装在任务中 - 这会将执行从 UI 线程移动到 bacckground:

private Task<bool> ISNeededFilesAvailable()
{ 
return Task.Run(()=>{   
try{
IsBusy = true; 
if(!File.Exist("MyCustomeControls.dll"))
return false
if(!File.Exist("PARSGREEN.dll"))
return false
return true;
}
finally
{
IsBusy = false;
}
});
}
private async void StartupWindow_Loaded(object sender, RoutedEventArgs e)
{
if (! (await ISNeededFilesAvailable()))
Application.close();
else
this.close();
}

您可以使用 IsBusy 来显示例如不确定的进度条,以向用户显示正在发生的事情。甚至可以更改光标以获得更好的反馈。

最新更新