CancellationToken 是否删除文件锁定?

Does CancellationToken removes file lock?

我有以下异步函数:

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;
                }

            });
    }

您可以看到它从文件中读取数据。我的问题是,如果我将 CancellationToken 用于异步方法,它会在使用块时删除文件锁定吗?

不,取消令牌本身不会执行任何操作(特别是不会关闭文件)。任务的代码需要反复检查令牌的状态并相应地执行取消操作。

目前还不清楚你打算在你的案例中在哪里使用取消令牌,因为没有重复的操作......但是由于代码已经正确设置了 using(…){} 语句,无论你在哪里中断操作文件将在 using (var read = new FileStream(....

finally 块中正确关闭