none
increment of values in string cross class instances RRS feed

  • Question

  • I have a value, its structure XXXXXXXXXX

    x== 0 to F

    what the best way to make the increment in this case?

    how can I make it thread safe?

    Thanks

    Monday, March 18, 2019 6:54 PM

Answers

  • Check one of solutions:

    static string avalue = "000BADF00D";

     

    static readonly object avaluelocker = new object();

     

    // . . .

     

    lock( avaluelocker )

    {

        ulong v = ulong.Parse( avalue, System.Globalization.NumberStyles.HexNumber );

        avalue = ( v + 1 ).ToString( "X10" );

    }

    • Edited by Viorel_MVP Monday, March 18, 2019 8:13 PM
    • Marked as answer by want 2 Learn Monday, March 18, 2019 8:43 PM
    Monday, March 18, 2019 8:08 PM

All replies

  • So, essentially, you have a string that is a hex number and you want to increment it.

    I would recommend the approach of storing the value in binary inside a separate variable (of type long, since you need 10 hex digits), and then convert the variable to hex whenever you need to use the value in its string form.

    The advantage of keeping the value in its binary form is that you have a very efficient method of incrementing it in a thread-safe way: just use the Interlocked.Increment method:

    https://docs.microsoft.com/en-us/dotnet/api/system.threading.interlocked.increment?view=netframework-4.7.2

    This is thread-safe and doesn't require any locking.

    • Proposed as answer by DerChris88 Monday, March 18, 2019 8:07 PM
    Monday, March 18, 2019 8:02 PM
    Moderator
  • Check one of solutions:

    static string avalue = "000BADF00D";

     

    static readonly object avaluelocker = new object();

     

    // . . .

     

    lock( avaluelocker )

    {

        ulong v = ulong.Parse( avalue, System.Globalization.NumberStyles.HexNumber );

        avalue = ( v + 1 ).ToString( "X10" );

    }

    • Edited by Viorel_MVP Monday, March 18, 2019 8:13 PM
    • Marked as answer by want 2 Learn Monday, March 18, 2019 8:43 PM
    Monday, March 18, 2019 8:08 PM
  • thanks!

    this is much faster (less then half time)

    then this solution

    Arbitrary to Decimal Numeral System Conversion in C#

    Monday, March 18, 2019 8:44 PM