473,699 Members | 2,552 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 1880
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
2363
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
3801
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
12228
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
8687
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
8617
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
9174
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...
0
9035
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
7751
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
6534
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
5875
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
4629
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3057
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

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.