473,587 Members | 2,479 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 4097
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.co m>
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.co m>
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
2202
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(*) where I want to receive tuples of (item1, item2, item3) from the iterables. But it doesn't work well for a situation like: zip(*tuple_iter)
18
2281
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 of a performance hit I'm taking using this technique versus using 'copy' to copy directly into a container with elements in place? Thanks, d
1
1891
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 // (i.e. as rbegin, rend was passed) } How can I call lexicographical_compare inside the function so that it traverses the range backwards?
3
2910
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 kinds of iterators on say a vector. OR is it that any iterator declared on Vector is Random Iterator which has the functionality of all the others.
8
1986
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 function where I with the help of iterators want to search through the container and remove a certain object in the container. Here is part of the code in that function:
24
3935
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 = s2 = s3 = for value in ???(s1, s2, s3):
2
2337
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
3394
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
2101
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
7852
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
7974
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8221
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6629
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
5719
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5395
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
3882
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1455
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1192
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.