If you use lock (model), it doesn't mean that other threads won't be able to access model. What it means is that two threads won't be able to execute a section protected by lock (model) at the same time. Because of this, you could use something like lock (model) to protect access to score too.
But that wouldn't work in this case. lock doesn't lock on a variable, it locks on an object and you modify which object model refers to in the loop. Because of that, I thin the best option here is to create another object and lock on that:
object model;
int score;
object modelLock = new object();
Parallel.For(…, (…) =>
{
int tempScore=0;
Object tempModel=getModel();
//some interesting stuff modifying value of tempScore
lock (modelLock)
{
if(tempScore > score)
{
score=tempScore;
model=tempModel;
}
}
});
If you find out that this is too slow for your needs (because using lock does have some overhead, which might be significant for you), you should consider using something like Thread.VolatileRead() or Interlocked.CompareExchange(). But be very careful with them, because it's very easy to make your code subtly wrong.