473,398 Members | 2,812 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,398 software developers and data experts.

C# 2.0 iterators and lock

Are there any issues I should be worried about when using C# 2.0 iterators
in conjunction with lock, i.e.

public IEnumerator GetEnumerator()
{
lock (lockObject)
{
foreach (object obj in collection)
{
yield return obj;
}
}
}

When precisely is the lock/unlock happening with respect to the iteration?
Lock & unlock once only when the iterator object is created? Lock & unlock
with each iteration? Lock before first iteration & unlock on disposal after
last iteration?
Sep 9 '08 #1
8 4082
On Sep 9, 4:15*pm, "Clive Dixon" <clived at digita dot comwrote:
Are there any issues I should be worried about when using C# 2.0 iterators
in conjunction with lock, i.e.

public IEnumerator GetEnumerator()
{
* * lock (lockObject)
* * {
* * * * foreach (object obj in collection)
* * * * {
* * * * * * yield return obj;
* * * * }
* * }

}

When precisely is the lock/unlock happening with respect to the iteration?
Lock & unlock once only when the iterator object is created? Lock & unlock
with each iteration? Lock before first iteration & unlock on disposal after
last iteration?
It would lock before the first, and after the last (or disposal). This
is a really bad thing to do - you shouldn't lock for indeterminate
amounts of time.

Jon
Sep 9 '08 #2
It would lock before the first, and after the last (or disposal). This
is a really bad thing to do - you shouldn't lock for indeterminate
amounts of time.
Hm, that's what I feared it would do; to confirm I wrote a class and
examined in Reflector. It looks to me however that the locking/unlocking is
done only within MoveNext (plus unlocking in Dispose in case an exception is
thrown), and not anywhere else. I really would have expected it to behave as
you say, but it looks like the locking behaviour changes once you use C# 2.0
iterators. Yuk.
Sep 9 '08 #3
On Sep 9, 4:45*pm, "Clive Dixon" <clived at digita dot comwrote:
It would lock before the first, and after the last (or disposal). This
is a really bad thing to do - you shouldn't lock for indeterminate
amounts of time.

Hm, that's what I feared it would do; to confirm I wrote a class and
examined in Reflector. It looks to me however that the locking/unlocking is
done only within MoveNext (plus unlocking in Dispose in case an exceptionis
thrown), and not anywhere else. I really would have expected it to behaveas
you say, but it looks like the locking behaviour changes once you use C# 2.0
iterators. Yuk.
That's the behaviour I described though. It will lock before the first
value is yielded, and won't unlock until either MoveNext() gets to the
end or a Dispose call.

There's no change to behaviour here - lock always has try/finally
semantics, and the finally blocks are only executed at the relevant
times. In other words, the iterator block logically "pauses" when it
hits a yield return statement.

I recently wrote a fairly detailed analysis of how iterator blocks are
compiled. See http://csharpindepth.com/Articles/Ch...mentation.aspx

Jon
Sep 9 '08 #4
>That's the behaviour I described though. It will lock before the first
value is yielded, and won't unlock until either MoveNext() gets to the
end or a Dispose call.
>There's no change to behaviour here - lock always has try/finally
semantics, and the finally blocks are only executed at the relevant
times. In other words, the iterator block logically "pauses" when it
hits a yield return statement.
>I recently wrote a fairly detailed analysis of how iterator blocks are
compiled. See
http://csharpindepth.com/Articles/Ch...mentation.aspx
>Jon
OK I see now. It was too late in the day for me to concentrate. I see now in
Reflector that the state machine looks as though it calls Monitor.Enter/Exit
only in certain states. I did read chapter 6 of your book last night on
iterators but the relevance to locking didn't click with me because I had
misread the disassembled code. When you point out that lock has try/finally
semantics it becomes obvious in one of those head slapping moments.

Thanks for the article, and keep up the good work.
Sep 10 '08 #5
<"Clive Dixon" <clived at digita dot com>wrote:
OK I see now. It was too late in the day for me to concentrate.
I know that feeling :)
I see now in Reflector that the state machine looks as though it
calls Monitor.Enter/Exit only in certain states.
It doesn't help that the generated code uses try/fault which doesn't
exist in normal C# and can be easily misread as try/finally!
I did read chapter 6 of your book last night on iterators but the
relevance to locking didn't click with me because I had misread the
disassembled code. When you point out that lock has try/finally
semantics it becomes obvious in one of those head slapping moments.

Thanks for the article, and keep up the good work.
Do you think it would be explicitly worth mentioning locks in the
article? I talk about using statements, but not locks...

--
Jon Skeet - <sk***@pobox.com>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon.skeet
C# in Depth: http://csharpindepth.com
Sep 10 '08 #6
>Thanks for the article, and keep up the good work.

Do you think it would be explicitly worth mentioning locks in the
article? I talk about using statements, but not locks...
It might be worth mentioning Jon, it's a potential pitfall for the unwary.
Sep 10 '08 #7
<"Clive Dixon" <clived at digita dot com>wrote:
>
Thanks for the article, and keep up the good work.
Do you think it would be explicitly worth mentioning locks in the
article? I talk about using statements, but not locks...

It might be worth mentioning Jon, it's a potential pitfall for the unwary.
Righto. I've added this paragraph:

<article>
It's worth remembering that most finally blocks in code aren't written
explicitly in C# - they're generated by the compiler as part of lock
and using statements. lock is particularly dangerous in iterator blocks
- any time you've got a yield return statement inside a lock block,
you've got a threading issue waiting to happen. Your code will keep
hold of the lock even when it has yielded the next value - and who
knows how long it will be before the client calls MoveNext() or
Dispose()? Likewise any try/finally blocks which are used for critical
matters such as security shouldn't appear in iterator blocks: the
client can deliberately prevent the finally block from executing if
they don't need any more values.
</article>

Do you think that covers it?

--
Jon Skeet - <sk***@pobox.com>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon.skeet
C# in Depth: http://csharpindepth.com
Sep 10 '08 #8
Do you think that covers it?
I think that should do the job - as you say, the important thing is the fact
that some try/finally are not explicitly stated in code and can whizz
straight over your head if you're not concentrating, like the lock example
did with me.
Sep 10 '08 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
by: Steven Bethard | last post by:
So, as I understand it, in Python 3000, zip will basically be replaced with izip, meaning that instead of returning a list, it will return an iterator. This is great for situations like: zip(*)...
18
by: deancoo | last post by:
I have gotten into the habit of often using copy along with an insert iterator. There are scenarios where I process quite a lot of data this way. Can someone give me a general feel as to how much...
1
by: Marcin Kaliciñski | last post by:
template<class RanAccIt> void some_algorithm(RanAccIt begin, RanAccIt end) { // this algorithm involves calling std::lexicographical_compare // on range [begin, end), and on reverse of this range...
3
by: codefixer | last post by:
Hello, I am trying to understand if ITERATORS are tied to CONTAINERS. I know the difference between 5 different or 6(Trivial, on SGI). But what I fail to understand is how can I declare all 5...
8
by: babak | last post by:
Hi everyone I have a problem with Iterators and containers in STL that hopefully someone can help me with. This is what I try to do: I have an associative (map) container and I have a...
24
by: Lasse Vågsæther Karlsen | last post by:
I need to merge several sources of values into one stream of values. All of the sources are sorted already and I need to retrieve the values from them all in sorted order. In other words: s1 = ...
2
by: ma740988 | last post by:
typedef std::vector < std::complex < double > > complex_vec_type; // option1 int main() { complex_vec_type cc ( 24000 ); complex_vec_type dd ( &cc, &cc ); } versus
90
by: John Salerno | last post by:
I'm a little confused. Why doesn't s evaluate to True in the first part, but it does in the second? Is the first statement something different? False print 'hi' hi Thanks.
18
by: desktop | last post by:
1) I have this code: std::list<intmylist; mylist.push_back(1); mylist.push_back(2); mylist.push_back(3); mylist.push_back(4);
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.