【发布时间】:2019-07-30 13:12:11
【问题描述】:
所以我收到异常“进程无法访问文件,因为它被另一个进程使用了。
当我调用这个特定方法时会显示异常:
public async static Task<bool> DownloadFileFromFTP(string PathToFile, string AppName)
{
return await Task.Run(() => {
if (File.Exists("settings.xml"))
{
XmlSerializer xs = new XmlSerializer(typeof(Information));
FileStream read = new FileStream("settings.xml", FileMode.Open, FileAccess.Read, FileShare.Read);
Information info = (Information)xs.Deserialize(read);
try
{
FtpClient client = new FtpClient(info.HDSynologyIP);
string a = info.FtpPassword;
string FTPPassword = EncryDecryptor.Decrypt(a);
client.Credentials = new NetworkCredential(info.FtpUsername, FTPPassword);
client.Connect();
bool finish = client.DownloadFile(@info.Downloads + "\\" + AppName, PathToFile, FtpLocalExists.Overwrite, FluentFTP.FtpVerify.Retry);
if (finish == true)
{
client.Disconnect();
read.Close();
return true;
}
else
{
client.Disconnect();
read.Close();
return false;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
read.Close();
}
read.Close();
}
else
{
MessageBox.Show("Missing settings.xml file");
return false;
}
return false;
});
}
并像这样在另一个类中调用它:
await General_Functions.DownloadFileFromFTP("Ultra_Script/Basic_SW/Adobe_Reader.exe", "Adobe_Reader.exe");
之前它不是异步的,但我不得不将它改造成异步方法。但我认为我正确地关闭了读者和客户。可能是异步方法的问题吗?因为我在异步之前没有这个问题。
谁能解释我做错了什么?
注意,我使用的是来自https://github.com/robinrodricks/FluentFTP 的FluentFTP。
【问题讨论】:
-
您知道使用
using为您拨打Dispose吗? -
我看不到在那里使用
await的巨大好处,因为无论如何你都在旋转一个新的Task。是什么让您认为它在这里有用? -
异常堆栈跟踪是什么?
-
Adobe_Reader.exe已经运行了吗?你检查任务管理器了吗? -
@mjwills 顺便说一句,我正在学习异步方法的工作原理,所以我尝试异步执行所有操作只是为了学习。但它不是让应用程序在做任务时更负责任吗?没有 Adobe_Reader 根本没有运行没有代码可以打开它,只需从 ftp 存储库下载它
标签: c# asynchronous dispose fluentftp