Say I have an object whose members I’d like to use in two separate tasks. What would be the best approach? Since a struct passes by value should I change the object to a struct and then create two separate copies of the object, and pass that to the two tasks? Also since the object’s properties are coming from a database I suppose I could create instances inside of each task.
Which approach would be the most efficient?
As hinted by Henk in the comments on the OP…
If the object’s properties are being used solely for reference, there’s no problem with instantiating the object once and passing it in to multiple tasks, however, if the tasks are going to be changing properties on the object, you need to deal with all the usual multi-threading issues.
In addition, since you mention that these objects represent Db records, I’d guess you’re getting them from an ORM. If you’re using the Entity Framework, the proxy classes it creates are definitely not thread-safe when changing properties.
So really, it depends on your usage I’d be tempted to do it all inside each task so the task is a stand-alone unit and later changes to the work it does by a developer unaware of this limitation won’t result in unexpected race conditions. (Assuming your’re not dealing with a large number of entities and memory usage is not a concern)