C#C
C#2y ago
CrosRoad95

Thread safe moving value between two objects

I have problem. Consider following class:
public class Foo {
  public int Amount { get; set; }
  public int MaxAmount { get; set; }
}

var foo1 = new Foo{ Amount = 75, MaxAmount = 100 };
var foo2 = new Foo{ Amount = 75, MaxAmount = 100 };

what i want to do is to thread safe move amount from one "Foo" object, to another that it won't overflow above "MaxAmount".
foo1.Transfer(foo2, 25); // Ok, foo2 now is full, foo1 have amount 50, foo2 amount 100
foo1.Transfer(foo2, 25); // Throw overflow exception, because 100 + 25 > 125
foo1.Transfer(foo2, 100); // Throw other exception, because now foo1 have Amount = 50


A bif more context: It is for game for items stacking purpose, it is used server side so two clients at once may attempt to move items.

Please focus on thread safety aspect
Was this page helpful?