Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 

45 linhas
1.4 KiB

  1. using System.Threading;
  2. using System.Threading.Tasks;
  3. using Microsoft.VisualStudio.TestTools.UnitTesting;
  4. using MQTTnet.Internal;
  5. namespace MQTTnet.Core.Tests
  6. {
  7. [TestClass]
  8. public class AsyncLockTests
  9. {
  10. [TestMethod]
  11. public void AsyncLock()
  12. {
  13. const int ThreadsCount = 10;
  14. var threads = new Task[ThreadsCount];
  15. var @lock = new AsyncLock();
  16. var globalI = 0;
  17. for (var i = 0; i < ThreadsCount; i++)
  18. {
  19. #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
  20. threads[i] = Task.Run(async () =>
  21. {
  22. await @lock.EnterAsync(CancellationToken.None);
  23. try
  24. {
  25. var localI = globalI;
  26. await Task.Delay(10); // Increase the chance for wrong data.
  27. localI++;
  28. globalI = localI;
  29. }
  30. finally
  31. {
  32. @lock.Exit();
  33. }
  34. });
  35. #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
  36. }
  37. Task.WaitAll(threads);
  38. Assert.AreEqual(ThreadsCount, globalI);
  39. }
  40. }
  41. }