public void SymmetricAlgorithmVerifierNegativeThreadingTest() { // Synchronization state object lockCheckParameter = new object(); SymmetricAlgorithm encryptorInstance = null; bool lockChecked = false; SymmetricAlgorithmDiagnosticOptions diagnosticOptions = new SymmetricAlgorithmDiagnosticOptions { CheckThreadSafety = true, LockCheckParameter = lockCheckParameter, LockCheckCallback = delegate(CryptographyLockContext <SymmetricAlgorithm> lockCheck) { Assert.AreSame(lockCheck.Parameter, lockCheckParameter, "Unexpected lock check parameter"); Assert.AreSame(lockCheck.Algorithm, encryptorInstance, "Unexpected algorithm check parameter"); lockChecked = true; return(false); } }; // Encryption state bool encryptionSucceeded = true; Exception encryptionException = null; try { encryptorInstance = new AesManaged(); SymmetricAlgorithm encryptor = encryptorInstance.EnableLogging(diagnosticOptions); // Thread to do the encryption Thread encryptionThread = new Thread(delegate() { try { using (MemoryStream ms = new MemoryStream()) using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write)) { byte[] plainText = Encoding.UTF8.GetBytes("Secret round trip message"); cs.Write(plainText, 0, plainText.Length); cs.FlushFinalBlock(); } encryptionSucceeded = true; } catch (Exception e) { encryptionException = e; encryptionSucceeded = false; } }); encryptionThread.Start(); encryptionThread.Join(); } finally { if (encryptorInstance != null) { (encryptorInstance as IDisposable).Dispose(); } } // Verify that our lock check was called, that we failed encryption, and that we got the correct exception Assert.IsTrue(lockChecked, "Lock check callback was not performed"); Assert.IsFalse(encryptionSucceeded, "Encryption should not have succeeded"); Assert.IsInstanceOfType(encryptionException, typeof(CryptographicDiagnosticException), "Did not get expected exception"); }