简体   繁体   中英

Different results from simple addition when in debug vs. non-debug

Environment is VS 2010 Express, C#. The following code yields different results when debugging versus not debugging.


        MyClass.Counter++;

        Debug.Write(MyClass.Counter.ToString());

        db.ExecuteCommand("update mytable set pct = {0}, reps = {1},is_active = 0," +
                "completed = 1,date_completed={2} " +
                "where my_id = {3} and myother_id = {4} and yetanother_id = 50",
                 aValue, MyClass.Counter, DateTime.Now, AnId, AnotherId);

When in debug mode or when using the Debug.Write statement if MyClass.Counter starts at zero, the result on the database afer the update is 1 ... as expected.

When I run this code without the debugger or using the Debug.Write statement the result on the database is 2. I tried everything I know to figure out how the integer gets incremented from 0 to 2 with one ++. I have even used interim variables ..ie int i = MyClass.Counter; i = i + 1; then use i in the ExecuteCommand....results are always the same, I go from 0 to 2.

Thanks for any response.

Assuming

public class MyClass 
{
    public static int Counter;
}

I would recommend:

db.ExecuteCommand("update mytable set pct = {0}, reps = {1},is_active = 0," +
        "completed = 1,date_completed={2} " +
        "where my_id = {3} and myother_id = {4} and yetanother_id = 50",
         aValue, MyClass.Counter++, DateTime.Now, AnId, AnotherId);

This will increment Counter after it's initial value is used. I don't know how come you would have different output in the debug view versus non-debug.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM