Created
January 1, 2020 08:43
-
-
Save xsoheilalizadeh/d0c929d0fd90abdc8597354ca9f255ef to your computer and use it in GitHub Desktop.
Interlocked
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.Collections.Generic; | |
| using System.Threading.Tasks; | |
| namespace Interlocked | |
| { | |
| class Program | |
| { | |
| static void Main(string[] args) | |
| { | |
| int tasksCount = 67; | |
| var tasks = new List<Task>(); | |
| var sharedCounter = new RequestCounter(); | |
| for (int i = 0; i < tasksCount; i++) | |
| { | |
| var task = Task.Factory.StartNew(() => { sharedCounter.AddRequest(); }); | |
| tasks.Add(task); | |
| } | |
| Task.WaitAll(tasks.ToArray()); | |
| Console.WriteLine($"Actual: {sharedCounter.GetCount()}, expected: {tasksCount}"); | |
| Console.ReadKey(); | |
| } | |
| } | |
| public class RequestCounter | |
| { | |
| private int _totalsRequests; | |
| public void AddRequest() | |
| { | |
| // none thread-safe | |
| // _totalsRequests++; | |
| // thread-safe | |
| System.Threading.Interlocked.Increment(ref _totalsRequests); | |
| } | |
| public int GetCount() | |
| { | |
| return _totalsRequests; | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment