异步void完成后运行void

时间:2016-04-25 20:53:17

标签: c# asynchronous encryption task

我正在异步加密文件,之后我想运行一个void来对加密文件做一些逻辑。我希望编译器等到文件完全加密。 那么我怎么能等待它完成呢?我可以使用"任务"? 感谢。

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");

    }

1 个答案:

答案 0 :(得分:2)

您无法知道dataType:方法何时完成。这正是你几乎从不使用$.ajax({ url: "test.json", dataType: "json" }, function(data) { ... }); 方法的原因。该方法应返回async void,以便调用者可以使用async void来确定方法何时完成,结果是什么(如果适用)以及是否成功,取消,或出现故障。