Skip to content

Instantly share code, notes, and snippets.

@xsoheilalizadeh
Created January 1, 2020 08:43
Show Gist options
  • Select an option

  • Save xsoheilalizadeh/d0c929d0fd90abdc8597354ca9f255ef to your computer and use it in GitHub Desktop.

Select an option

Save xsoheilalizadeh/d0c929d0fd90abdc8597354ca9f255ef to your computer and use it in GitHub Desktop.
Interlocked
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