I have following async function:
private async Task<bool> ValidateFtpAsync()
{
return await Task.Run(
() =>
{
if(File.Exists("settings.xml"))
{
var xs = new XmlSerializer(typeof(Information));
using (var read = new FileStream("settings.xml", FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
{
Information info = (Information)xs.Deserialize(read);
try
{
var DecryptedInfo = FileCryptoDecryptor.ReadEncryptedConfiguration("hakuna.xml.aes", Global_Variables.AppPassword);
string DecryptedFTPPass = EncryDecryptor.Decrypt(DecryptedInfo.FtpPassword, "UltraSecretPasswordNotGonnaSayItToYou");
return General_Functions.isValidConnection(info.HDSynologyIP, info.FtpUsername, DecryptedFTPPass);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
return false;
}
else
{
MessageBox.Show("Missing settings file.");
return false;
}
});
}
You can see it reads data from a file. My question is if i use CancellationToken for async method does it remove file lock when its in using block?
No, cancellation token by itself does not do anything (and in particular does not close files). The task's code needs to check state of the token repeatedly and act accordingly to perform cancellation.
It is unclear where do you plan to use a cancellation token in your case as there is no repeated operations... But since code has properly set with using(…){}
statements irrespective where you break the operation the file will be correctly closed in finally
block of using (var read = new FileStream(...
.