Search code examples
c#interlocked

How can I use an array item with Interlocked.CompareExchange


I'm familiar with using Interlocked.CompareExchange() with plain objects. However I'd like to use it with the member of an array:

string[] myArray = new string[] { "A", "B", "C" }; 
string myStr = (string) Interlocked.CompareExchange(ref myArray[0], null, myArray[0]); 
// myArray[0] == null

How can I accomplish this?


Solution

  • I am using it like this

    string[] myArray = new string[] { "A", "B", "C" };
            string myStr = Interlocked.CompareExchange(ref myArray[0], "F", myArray[0]);
            foreach (var item in myArray)
            {
                Console.WriteLine(item.ToString());
            }
    

    And this is the out put

    F B C
    

    Everything is Fine.