开发者

A integer isn't upgraded by a thread c#

I have declared in C# a static public int then that int is suplyed to a thread in it's constructor the thread's job is very simple to increment it but it doesn't happen Here I declare the static value:

class Global
{
    static public  int hardcap = 100;
    public int speed;
    static public Semaphore myhitpoints = new Semaphore(1, 1);
    static public Semaphore oponenthitpoints = new Semaphore(1, 1);
   static  public int mhp = 100;
    static public int ohp = 100;
    static public int mmana = 0;
    static public int omana = 0;
  public static Charm dragonblade = new   Charm(10, 30, 3, myhitpoints, oponenthitpoints, mhp, ohp, "dragon blade", mmana);
  public  static  Charm dragonshield = new Charm(30, 10, 5, myhitpoints, oponenthitpoints, mhp, ohp, "dragon 开发者_JAVA技巧shield", mmana);
    public static Charm b1charm;
    public static  Charm b2charm;
    public static Opponent enemy;

}

class ManaWell
    {
        int mana_regen;
        int cap = 1000;
        int target;
        public ManaWell(int x, int y)
        {
           mana_regen = x;
            target = y;
        }
        public void Refill()
        {
            while (true)
            {
               // if (this.target + mana_regen <= cap)
                if (target+mana_regen<cap)
                {
                    Thread.Sleep(3000);
                    target += mana_regen;
                    MessageBox.Show(target.ToString());

                }
            }
        }
    }
 ManaWell mw1 = new ManaWell(20,Global.mmana);
        ManaWell mw2 = new ManaWell(20,Global.omana);

        Thread tmw1 = new Thread(new ThreadStart(mw1.Refill));
        Thread tmw2 = new Thread(new ThreadStart(mw2.Refill));

        tmw1.Start();
        tmw2.Start();

So target works fine but y won't increase.


Integer is passed as value and gets locally increased. it will not increase the statical variable which you pass in

Value vs Reference Types

If you want that your external static variable gets updated you could use the ref keyword.

Beside that you should synchronize the access to the variable as you access it from several threads...

if you have "targets" which should be stored and called later you should pass a delegate (which is pointing to the update method) to the constructor. this delegate you can store and call later


When you create your ManaWell object and pass in a variable, it will only be the variable's value that is assigned to target. So when you add to target, you are doing only that; the passed-in variable will not be affected (as you're seeing.)

If you're really passing in a public static int, then to increase it, just do math on it directly (and you don't even have to pass it in):

MyClass.MyStaticInt += aNumber;


The reason is that the value of the variable is passed to the constructor. You are only incrementing the variable local to your class.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜