473,698 Members | 2,361 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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(b mp);
bmp = new Bitmap("y.jpg") ;
Monitor.Exit(bm p);

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 1878
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.publi c.dotnet.langua ges.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(b mp);
bmp = new Bitmap("y.jpg") ;
Monitor.Exit(bm p);

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.publi c.dotnet.langua ges.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(b mp);
bmp = new Bitmap("y.jpg") ;
Monitor.Exit(bm p);

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.c om> 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(b mp);
bmp = new Bitmap("y.jpg") ;
Monitor.Exit(bm p);
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.c om> 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(b mp);
bmp = new Bitmap("y.jpg") ;
Monitor.Exit(bm p);

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.co m>
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******@devel op.com> wrote in message
news:%2******** *******@TK2MSFT NGP12.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.publi c.dotnet.langua ges.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(b mp);
bmp = new Bitmap("y.jpg") ;
Monitor.Exit(bm p);

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.publi c.dotnet.langua ges.csharp]

Nov 16 '05 #7
Brett Robichaud <br************ @nospam.yahoo.c om> 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.co m>
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.TryEnte r 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.publi c.dotnet.langua ges.csharp/<MP************ ************@ms news.microsoft. com>

Brett Robichaud <br************ @nospam.yahoo.c om> 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.co m>
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.publi c.dotnet.langua ges.csharp]
Nov 16 '05 #9
Richard Blewett [DevelopMentor] <ri******@devel op.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.TryEnte r 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.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #10

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

Similar topics

0
451
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 would let two locked blocks to execute simulatenously. As I moved onto implemeting Abort, I wondered how Thread.Abort() could possibly abort a thread but yet maintain monitor consistancy. For example,
44
2362
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 thread. The worker thread is reading the serial port, waiting for something to happen (a service request). When it does it raises an event. Of course, the event is executed on the worker thread. The idea is that when the event is raised, the handler...
13
7460
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
5847
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 component becomes instabile, throwing a Windows like error (access violation on 0x00000002), not an framework exception. The component and all of its subcomponents are 100% managed code. What could go wrong with Thread.Abort()? Thanks for any hints.
3
1795
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 done. Here's an example of what I'm doing: ==================================== private void button1_Click(object sender, System.EventArgs e) {
0
285
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 inside it's "read loop" waiting for data from the client. I find that many times while inside the "read loop" it missed many of the value that was assigned to the public Message variable. For example, the main program send number 1 thru 100, but...
5
1643
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 while inside it's "read loop" waiting for data from the client. In the main program, I check to see if the Message member has been cleared before changing its value, that way you know it has been written by the
5
3800
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 mysql connections open so I end up with quite a few at the end. Is there a different way that I should do this? class Program { static string categories = { "emulation" , "audio" , "console" , "anime" , "xxx" , "tv" , "pictures" , "video" };
5
12227
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 event handlers may take longer than the interval for either of the timers, so it's possible for multiple events to fire "simultaneously" and for events to queue up. I'm attempting to get the timers to sync on some reference type object, or use...
0
8674
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8603
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,...
0
9157
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8895
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
8861
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...
1
6518
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...
1
3046
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2329
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2001
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.