25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.

AsyncLockTests.cs 1.3 KiB

123456789101112131415161718192021222324252627282930313233343536373839
  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. }