Search code examples
c#multithreadinglockingtaskinterlocked

lock vs Interlocked.Exchange


I have an application which constantly (+-100ms) reads orders from a PLC and then puts them in a model which then gets read by multiple clients. For this im using the lock statement.

Order Reading thread :

lock (model) {
//update object
}

Clients Reading :

lock (model) {
//serialize object to json string
}
send over tcp stream to client.

But i could also use for the update :

Interlocked.ExChange(oldObj, newObj)

I don't want my clients to have to wait for a lock that is happening in the Order Reading thread. And i definitly dont want client to block my Order Reading thread.

Am i better off using the Interlocked ?

Thanks for the advice!


Solution

  • Yes, you are better off using Interlocked as it's more efficient since it's mostly translated into a single atomic operation.

    However, if you don't mind the clients still reading the old object for a bit you can even do without the Interlocked and just set a new instance.

    The client that happen to get the new instance will get the updated data and those that don't will get it in one of the next checks.