, downvotes, :).
.
- , , WinAPI , , , , , RunMe , , , 2.
Try a look at atomic operations. For your scenario, this will work very well, Interlocked.Increment (ref sum). From there, you should limit yourself to direct access to the amount, but this is not a problem, because the Increment method returns the last result.
Another option is to use SpinLock, that is, IF YOU WORK REALLY QUICKLY. NEVER INCLUDE something like Console.WriteLine or any other system operations or lengthy calculations, etc.
Here are the Inrelocked examples:
using System;
using System.Threading;
using System.Threading.Tasks;
class ThreadTest
{
private static int sum;
private static int Add(int add) => Interlocked.Add(ref sum, add);
private static int Increment() => Interlocked.Increment(ref sum);
private static int Latest() => Interlocked.Add(ref sum, 0);
private static void RunMe() => Increment();
static void Main()
{
Task t1 = new Task(RunMe);
Task t2 = new Task(RunMe);
t1.Start();
t2.Start();
Task.WaitAll(t1, t2);
Console.WriteLine(Latest().ToString());
Console.ReadLine();
}
}
source
share