473,387 Members | 1,592 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,387 software developers and data experts.

Thread.Monitor & references

I need to make access to a reference object threadsafe. My natural instinct
was to simply use Monitor.Enter() and Exit(). The problem is that the
object behind the reference changes frequently, so my understanding of
Monitor indicates this would not protect my object. Example:

Bitmap bmp = new Bitmap("x.jpg");
Monitor.Enter(bmp);
bmp = new Bitmap("y.jpg");
Monitor.Exit(bmp);

The above doesn't do when one might expect, correct? My C++ head says to me
that what I really want to do is protect the 'pointer', not thing 'thing
pointed to', since I have no other pointers to this thing. But I'm in C# now
and my head is baffled.

So currently I am using a Mutex to protect this kind of data, but it seems
more klunky. Is there any way to use the slick Monitor (or lock) syntax and
still protect this situation?

-Brett-
Nov 16 '05 #1
12 1855
Why not just declare an invariant companion to the Bitmap

object bitmapGuard = new object();

and lock the guard instead

Regards

Richard Blewett - DevelopMentor
http://staff.develop.com/richardb/weblog

nntp://news.microsoft.com/microsoft.public.dotnet.languages.csharp/<O0**************@TK2MSFTNGP10.phx.gbl>

I need to make access to a reference object threadsafe. My natural instinct
was to simply use Monitor.Enter() and Exit(). The problem is that the
object behind the reference changes frequently, so my understanding of
Monitor indicates this would not protect my object. Example:

Bitmap bmp = new Bitmap("x.jpg");
Monitor.Enter(bmp);
bmp = new Bitmap("y.jpg");
Monitor.Exit(bmp);

The above doesn't do when one might expect, correct? My C++ head says to me
that what I really want to do is protect the 'pointer', not thing 'thing
pointed to', since I have no other pointers to this thing. But I'm in C# now
and my head is baffled.

So currently I am using a Mutex to protect this kind of data, but it seems
more klunky. Is there any way to use the slick Monitor (or lock) syntax and
still protect this situation?

-Brett-

---
Incoming mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.771 / Virus Database: 518 - Release Date: 28/09/2004

[microsoft.public.dotnet.languages.csharp]
Nov 16 '05 #2
hi
you can either use lock block or Mutex itself
regards
ansil

"Brett Robichaud" wrote:
I need to make access to a reference object threadsafe. My natural instinct
was to simply use Monitor.Enter() and Exit(). The problem is that the
object behind the reference changes frequently, so my understanding of
Monitor indicates this would not protect my object. Example:

Bitmap bmp = new Bitmap("x.jpg");
Monitor.Enter(bmp);
bmp = new Bitmap("y.jpg");
Monitor.Exit(bmp);

The above doesn't do when one might expect, correct? My C++ head says to me
that what I really want to do is protect the 'pointer', not thing 'thing
pointed to', since I have no other pointers to this thing. But I'm in C# now
and my head is baffled.

So currently I am using a Mutex to protect this kind of data, but it seems
more klunky. Is there any way to use the slick Monitor (or lock) syntax and
still protect this situation?

-Brett-

Nov 16 '05 #3

"Brett Robichaud" <br************@nospam.yahoo.com> a écrit dans le message
de news: O0**************@TK2MSFTNGP10.phx.gbl...
I need to make access to a reference object threadsafe. My natural
instinct
was to simply use Monitor.Enter() and Exit(). The problem is that the
object behind the reference changes frequently, so my understanding of
Monitor indicates this would not protect my object. Example:

Bitmap bmp = new Bitmap("x.jpg");
Monitor.Enter(bmp);
bmp = new Bitmap("y.jpg");
Monitor.Exit(bmp);
Reference assignment is atomic. So, if all you do is reassign the bmp
variable, you don't need to protect it with Monitor.Enter/Exit

If you need to protect a block of code rather than a single assignment, you
should lock on a stable object rather than on a reference that changes all
the time. If you don't have any such object, you can always create one:
static readonly object MyLock = new object();

Bruno.

The above doesn't do when one might expect, correct? My C++ head says to
me
that what I really want to do is protect the 'pointer', not thing 'thing
pointed to', since I have no other pointers to this thing. But I'm in C#
now
and my head is baffled.

So currently I am using a Mutex to protect this kind of data, but it seems
more klunky. Is there any way to use the slick Monitor (or lock) syntax
and
still protect this situation?

-Brett-

Nov 16 '05 #4
> Reference assignment is atomic. So, if all you do is reassign the bmp
variable, you don't need to protect it with Monitor.Enter/Exit


As long as you don't really care if other threads may get the old value
rather than the new one shortly after your assignment (sometimes, this is
harmless). If you care, you should use Monitor.Enter/Exit (or the volatile
keyword).

Bruno.
Nov 16 '05 #5
Brett Robichaud <br************@nospam.yahoo.com> wrote:
I need to make access to a reference object threadsafe. My natural instinct
was to simply use Monitor.Enter() and Exit(). The problem is that the
object behind the reference changes frequently, so my understanding of
Monitor indicates this would not protect my object. Example:

Bitmap bmp = new Bitmap("x.jpg");
Monitor.Enter(bmp);
bmp = new Bitmap("y.jpg");
Monitor.Exit(bmp);

The above doesn't do when one might expect, correct?
That depends on what you might expect :)

It doesn't do what you *want*, certainly.
My C++ head says to me
that what I really want to do is protect the 'pointer', not thing 'thing
pointed to', since I have no other pointers to this thing. But I'm in C# now
and my head is baffled.

So currently I am using a Mutex to protect this kind of data, but it seems
more klunky. Is there any way to use the slick Monitor (or lock) syntax and
still protect this situation?


Use a separate, unchanging reference for locking. See
http://www.pobox.com/~skeet/csharp/t...ckchoice.shtml for more
information.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #6
That would work, but isn't really all that different than the mutex
approach. Though it does allow me to use the lock syntax that I like so
much. I'll give it some thought.

-Brett-

"Richard Blewett [DevelopMentor]" <ri******@develop.com> wrote in message
news:%2***************@TK2MSFTNGP12.phx.gbl...
Why not just declare an invariant companion to the Bitmap

object bitmapGuard = new object();

and lock the guard instead

Regards

Richard Blewett - DevelopMentor
http://staff.develop.com/richardb/weblog

nntp://news.microsoft.com/microsoft.public.dotnet.languages.csharp/<O0**************@TK2MSFTNGP10.phx.gbl>
I need to make access to a reference object threadsafe. My natural instinct was to simply use Monitor.Enter() and Exit(). The problem is that the
object behind the reference changes frequently, so my understanding of
Monitor indicates this would not protect my object. Example:

Bitmap bmp = new Bitmap("x.jpg");
Monitor.Enter(bmp);
bmp = new Bitmap("y.jpg");
Monitor.Exit(bmp);

The above doesn't do when one might expect, correct? My C++ head says to me that what I really want to do is protect the 'pointer', not thing 'thing
pointed to', since I have no other pointers to this thing. But I'm in C# now and my head is baffled.

So currently I am using a Mutex to protect this kind of data, but it seems more klunky. Is there any way to use the slick Monitor (or lock) syntax and still protect this situation?

-Brett-

---
Incoming mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.771 / Virus Database: 518 - Release Date: 28/09/2004

[microsoft.public.dotnet.languages.csharp]

Nov 16 '05 #7
Brett Robichaud <br************@nospam.yahoo.com> wrote:
That would work, but isn't really all that different than the mutex
approach. Though it does allow me to use the lock syntax that I like so
much. I'll give it some thought.


Locks are also rather cheaper than mutexes, as they're entirely within
the CLR. And yes, lock is great :)

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #8
No, lock is terrible.

The concept of stack based synchronization primitve acquisition and release is great, and the fact that its's exception proof is great, but the lack of timeout sucks rocks. Infinite timeouts are a great way in multithreaded code to get unrecoverable deadlocks. Its much better to get the first 2 without the last by using a wrapper around Monitor.TryEnter rather than Monitor.Enter (which lock is). Look at Ian Griffiths' TimedLock implementation here

http://www.interact-sw.co.uk/iangblo...retimedlocking

Used in conjunction with the using statement it gives stack based, exception proof access and it supports timeouts.

Regards

Richard Blewett - DevelopMentor
http://staff.develop.com/richardb/weblog

nntp://news.microsoft.com/microsoft.public.dotnet.languages.csharp/<MP************************@msnews.microsoft.com >

Brett Robichaud <br************@nospam.yahoo.com> wrote:
That would work, but isn't really all that different than the mutex
approach. Though it does allow me to use the lock syntax that I like so
much. I'll give it some thought.


Locks are also rather cheaper than mutexes, as they're entirely within
the CLR. And yes, lock is great :)

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

---
Incoming mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.771 / Virus Database: 518 - Release Date: 28/09/2004

[microsoft.public.dotnet.languages.csharp]
Nov 16 '05 #9
Richard Blewett [DevelopMentor] <ri******@develop.com> wrote:
No, lock is terrible.

The concept of stack based synchronization primitve acquisition and
release is great, and the fact that its's exception proof is great,
but the lack of timeout sucks rocks. Infinite timeouts are a great
way in multithreaded code to get unrecoverable deadlocks.
True - however, given that possibility, I think I'd rather have the
deadlock not recover and the whole process terminate rather than try to
recover, personally. Deadlock is usually the sign of a disastrous
coding mistake rather than anything else. I take your point, but
wouldn't say that lock is terrible :)
Its much
better to get the first 2 without the last by using a wrapper around
Monitor.TryEnter rather than Monitor.Enter (which lock is). Look at
Ian Griffiths' TimedLock implementation here

http://www.interact-sw.co.uk/iangblo...retimedlocking

Used in conjunction with the using statement it gives stack based,
exception proof access and it supports timeouts.


That's nice, yes - I'll try to remember it for cases where I would
genuinely find it useful.

What I *do* think is a shame is that Monitor works the way it does,
with any object, rather than Enter etc being instance methods which
need to be called on Monitor instances which are specifically created.
That would get rid of all the code which locks "this" for no good
reason. (It would also save a bit of space for every object which
didn't need to keep a monitor reference for locking purposes, but
that's not the principal reason for it.)

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #10
The main thing about the TimedLock is rather than trying to work out why part or all of your application isn't responding, it throws an exception that makes it pretty obvious that you probably had a deadlock - and you have half of the story about what was going on (the exception trace).

And in some situations its better to be able to log and recover from a deadlock (granted its a bug) than crash your whole overnight batch run and have to get a 3rd line support dev out of bed to nurse the batch through till morning (assuming any of the operators had noticed the batch process had frozen in the first place)

Regards

Richard Blewett - DevelopMentor
http://staff.develop.com/richardb/weblog

nntp://news.microsoft.com/microsoft.public.dotnet.languages.csharp/<MP************************@msnews.microsoft.com >

Richard Blewett [DevelopMentor] <ri******@develop.com> wrote:
No, lock is terrible.

The concept of stack based synchronization primitve acquisition and
release is great, and the fact that its's exception proof is great,
but the lack of timeout sucks rocks. Infinite timeouts are a great
way in multithreaded code to get unrecoverable deadlocks.
True - however, given that possibility, I think I'd rather have the
deadlock not recover and the whole process terminate rather than try to
recover, personally. Deadlock is usually the sign of a disastrous
coding mistake rather than anything else. I take your point, but
wouldn't say that lock is terrible :)
Its much
better to get the first 2 without the last by using a wrapper around
Monitor.TryEnter rather than Monitor.Enter (which lock is). Look at
Ian Griffiths' TimedLock implementation here

http://www.interact-sw.co.uk/iangblo...retimedlocking

Used in conjunction with the using statement it gives stack based,
exception proof access and it supports timeouts.


That's nice, yes - I'll try to remember it for cases where I would
genuinely find it useful.

What I *do* think is a shame is that Monitor works the way it does,
with any object, rather than Enter etc being instance methods which
need to be called on Monitor instances which are specifically created.
That would get rid of all the code which locks "this" for no good
reason. (It would also save a bit of space for every object which
didn't need to keep a monitor reference for locking purposes, but
that's not the principal reason for it.)

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

---
Incoming mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.771 / Virus Database: 518 - Release Date: 28/09/2004

[microsoft.public.dotnet.languages.csharp]
Nov 16 '05 #11
Richard Blewett [DevelopMentor] <ri******@develop.com> wrote:
The main thing about the TimedLock is rather than trying to work out
why part or all of your application isn't responding, it throws an
exception that makes it pretty obvious that you probably had a
deadlock - and you have half of the story about what was going on
(the exception trace).
True. In a debug situation it's helpful to be able to just pause the
whole process and see what's going on, but in production an exception
is much better for diagnostic purposes than straight deadlock.
And in some situations its better to be able to log and recover from
a deadlock (granted its a bug) than crash your whole overnight batch
run and have to get a 3rd line support dev out of bed to nurse the
batch through till morning (assuming any of the operators had noticed
the batch process had frozen in the first place)


I think it depends - if you've got a major problem like that, the rest
of your overnight batch run might not just fail, but fail in a way
which damages data. I tend to be fairly cautious about this kind of
thing, preferring a complete restart to anything else :)

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #12
Well yes, you have to code for recovery - you're right that it doesn't happen by magic.

Regards

Richard Blewett - DevelopMentor
http://staff.develop.com/richardb/weblog

nntp://news.microsoft.com/microsoft.public.dotnet.languages.csharp/<MP************************@msnews.microsoft.com >

Richard Blewett [DevelopMentor] <ri******@develop.com> wrote:
The main thing about the TimedLock is rather than trying to work out
why part or all of your application isn't responding, it throws an
exception that makes it pretty obvious that you probably had a
deadlock - and you have half of the story about what was going on
(the exception trace).
True. In a debug situation it's helpful to be able to just pause the
whole process and see what's going on, but in production an exception
is much better for diagnostic purposes than straight deadlock.
And in some situations its better to be able to log and recover from
a deadlock (granted its a bug) than crash your whole overnight batch
run and have to get a 3rd line support dev out of bed to nurse the
batch through till morning (assuming any of the operators had noticed
the batch process had frozen in the first place)


I think it depends - if you've got a major problem like that, the rest
of your overnight batch run might not just fail, but fail in a way
which damages data. I tend to be fairly cautious about this kind of
thing, preferring a complete restart to anything else :)

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

---
Incoming mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.771 / Virus Database: 518 - Release Date: 28/09/2004

[microsoft.public.dotnet.languages.csharp]
Nov 16 '05 #13

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

Similar topics

0
by: Tum | last post by:
Hi, I've been working on DotGNU trying to implement the correct semantics for monitors, thread.abort (etc) in the runtime. Russell Stuart posted an example a few days ago which we discovered...
44
by: Charles Law | last post by:
Hi guys. I'm back on the threading gig again. It's the age-old question about waiting for something to happen without wasting time doing it. Take two threads: the main thread and a worker...
13
by: William Stacey | last post by:
Using the following code sample: public byte Get() { // <= Possible to switch Here?? lock(syncLock) { //Do something in Get(). } }
18
by: Urs Vogel | last post by:
Hi I wrote an application server (a remoting sinlgeton), where processes must be stopped in very rare cases, done thru a Thread.Abort(). Occasionally, and only after a Thread.Abort(), this...
3
by: GroZZleR | last post by:
Hey all, I'm threading newbie, I've never attempted it before. I've got a button that when clicked starts up a thread to process some files. This keeps my GUI responsive and gets the tasks...
0
by: fiefie.niles | last post by:
I am having problem with thread. I have a Session class with public string variable (called Message) that I set from my Main program. In the session class it checks for the value of Message while...
5
by: fniles | last post by:
I am having problem with thread. I have a Session class with public string variable (called Message) that I set from my Main program. In the session class it checks for the value of Message...
5
by: admin | last post by:
ok This is my main. Pretty much it goes through each category and starts up 4 worker threads that then ask for groups to gether from. My problem is that when the thread gets done it keeps the...
5
by: Tony Gravagno | last post by:
I have a class that instantiates two Timer objects that fire at different intervals. My class can be instantiated within a Windows Form or from a Windows Service. Actions performed by one of the...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
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...

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.