1

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);
}
cuongle
  • 74,024
  • 28
  • 151
  • 206
bobbo
  • 845
  • 2
  • 14
  • 24
  • More important: Is all other access to `m_transfers.Values` also being guarded? It looks like you might not need a `lock()` at all. – H H Sep 12 '12 at 11:29

3 Answers3

3

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 lock involves a try/finally, and at the IL level you can't ret from inside a try; so the compiler actually writes it like your first version).

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
1

Same as you don't have to do this in case of try, using, you don't have to do this here. Compiler puts needed bits of code for you on function exit.

Check this for more info: Monitor vs lock

Community
  • 1
  • 1
Bartosz
  • 3,318
  • 21
  • 31
0

both are valid.
as soon as you return execution comes out of the block.

Parv Sharma
  • 12,581
  • 4
  • 48
  • 80