异步作废完成后运行作废 [英] Run a void after an async void has been completed
问题描述
我正在异步加密文件,此后,我想运行一个void对加密的文件进行一些逻辑处理.我希望编译器等待文件完全加密后再使用. 那么如何等待它完成呢?我可以使用任务"吗? 谢谢.
I am encrypting a file asynchronously,and after that I want to run a void to do some logic on the encrypted file. I want the compiler wait until the file has been encrypted completely. So how can I wait for it to be completed? Have I to use "Task"? Thanks.
public static async void AES_Encrypt(string path, string Password,Label lbl,ProgressBar prgBar)
{
byte[] encryptedBytes = null;
FileStream fsIn = new FileStream (path, FileMode.Open);
byte[] passwordBytes = Encoding.UTF8.GetBytes (Password);
byte[] saltBytes = new byte[] { 8, 2, 5, 4, 1, 7, 7, 1 };
MemoryStream ms = new MemoryStream ();
RijndaelManaged AES = new RijndaelManaged ();
AES.KeySize = 256;
AES.BlockSize = 128;
var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);
AES.Key = key.GetBytes(AES.KeySize / 8);
AES.IV = key.GetBytes(AES.BlockSize / 8);
AES.Mode = CipherMode.CBC;
CryptoStream cs = new CryptoStream (ms, AES.CreateEncryptor (), CryptoStreamMode.Write);
byte[] buffer = new byte[1048576];
int read;
long totalBytes = 0;
while ((read = fsIn.Read (buffer, 0, buffer.Length)) > 0) {
totalBytes += read;
double p = Math.Round((double)totalBytes * 100.0 / fsIn.Length,2,MidpointRounding.ToEven);
lbl.Text = p.ToString ();
prgBar.Value = (int)p;
Application.DoEvents ();
await cs.WriteAsync(buffer,0,read);
}
cs.Close();
fsIn.Close ();
encryptedBytes = ms.ToArray();
ms.Close();
AES.Clear ();
string retFile = path + ".cte";
File.WriteAllBytes (retFile, encryptedBytes);
Console.WriteLine ("ok");
}
推荐答案
您无法知道async void
方法何时完成.这就是为什么您几乎不应该使用async void
方法的原因.该方法应返回Task
,以便调用方可以使用Task
来确定该方法何时完成,结果是什么(如果适用)以及是否成功,取消或出错.
You have no way of knowing when an async void
method has completed. That's exactly why you should virtually never be using an async void
method. The method should return a Task
so that that Task
can be used by the caller to determine when the method has finished, what the result(s) are (if applicable) and whether it was successful, cancelled, or faulted.
这篇关于异步作废完成后运行作废的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!