Não pode escolher mais do que 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.
 
 
 
 

40 linhas
1.3 KiB

  1. using System.Threading;
  2. using System.Threading.Tasks;
  3. using Microsoft.VisualStudio.TestTools.UnitTesting;
  4. using MQTTnet.Internal;
  5. namespace MQTTnet.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. using (var releaser = await @lock.WaitAsync(CancellationToken.None))
  23. {
  24. var localI = globalI;
  25. await Task.Delay(10); // Increase the chance for wrong data.
  26. localI++;
  27. globalI = localI;
  28. }
  29. });
  30. #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
  31. }
  32. Task.WaitAll(threads);
  33. Assert.AreEqual(ThreadsCount, globalI);
  34. }
  35. }
  36. }