This is possibly a silly question, but do I need to use and assignment with a lock, or can I simply return the results.
For example:
I have a private helper method that returns an IEnumerable list of file names. It uses a lock to ensure the method is thread safe while it is iterating around the m_transfers collection.
Do I need an assignment…
IEnumerable<String> updated;
lock (m_transfers.Lock)
{
updated = m_transfers.Values.Where(transfer => transfer.Updated)
.Select(transfer => transfer.Filename);
}
return updated;
Or can I just do
lock (m_transfers.Lock)
{
return updated = m_transfers.Values.Where(transfer => transfer.Updated)
.Select(transfer => transfer.Filename);
}
No, you don’t need to add an extra variable; the semantic is the same either way, since in either case we only actually return the value once we have relinquished the lock.
Since the variable doesn’t serve a purpose, I would remove it and use the second version – although technically, the compiler actually puts it back in anyway (a
lockinvolves atry/finally, and at the IL level you can’tretfrom inside atry; so the compiler actually writes it like your first version).