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

Writing multithreaded class in .net ( C#)

KK
Dear All
My requirement is to write class that is thread safe.( All public methods &
static methods must be thread safe ).
I found two options to implement this
1.using MethodImplOptions.Synchronized attribute
2.Using Lock statement

Class using method 1:
public class X
{

[MethodImpl(MethodImplOptions.Synchronized)]

public void X1()

{
}
[MethodImpl(MethodImplOptions.Synchronized)]

public void X2()
{

}
}

Class using method 2:
public class Y
{
public void Y1()
{
lock(this)
{
}
}
public void Y2()
{
lock(this)
{
}

}
}

Can somebody explain me what are the advantages & disadvantages with
these two approaches?

Thanks in advance.

Best Regards
Krishna
Mar 13 '06 #1
6 1512
KK wrote:
My requirement is to write class that is thread safe.( All public methods &
static methods must be thread safe ).
I found two options to implement this
1.using MethodImplOptions.Synchronized attribute
2.Using Lock statement


Using MethodImplOptions.Synchronized is equivalent to wrapping the body
of the method in:

lock (this)

or

lock (typeof(TheTypeInvolved))

I wouldn't recommend it, and I wouldn't recommend using "lock this"
anyway.

See http://www.pobox.com/~skeet/csharp/t...ckchoice.shtml for
reasons and recommendations.

Jon

Mar 13 '06 #2
Good article, and the one linked underneath it about an alternative (using)
syntax for Monitor; can I ask a quick question on the latter?

Firstly - the example code includes:

<quote>
// ... or if you want to be able to wait/pulse the monitor
using (LockToken token = syncLock.Lock(10000))
{
Monitor.Wait (token.Monitor);
// or
Monitor.Pulse (token.Monitor);
}
</quote>

First - looking at the code, I think this is a typo of syncLock.Monitor, but
my real question is: why make the monitor publicly visible at all? Why not
just have a SyncLock.Wait, SyncLock.Pulse and SyncLock.PulseAll (or better
still: LockToken.{Wait|Pulse|PulseAll}, since we really should own the lock
before calling these methods) that forwards via System.Threading.Monitor -
this would avoid callers having to mix implementations
(System.Threading.Monitor for some things, SyncLock / LockToken for others).
Also the SyncLock.monitor (field) could possibly be readonly (maybe it's
just my habit, but I tend to make my lock-objects readonly so I don't
accidentally break them by switching values - I'm sometimes clumsy that
way).

In case tone doesn't carry in an e-mail, I don't mean for this to sound
negative in any way - I think it's a very neat implementation : just some
thoughts and questions.

"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:11**********************@u72g2000cwu.googlegr oups.com...
KK wrote:
My requirement is to write class that is thread safe.( All public methods
&
static methods must be thread safe ).
I found two options to implement this
1.using MethodImplOptions.Synchronized attribute
2.Using Lock statement


Using MethodImplOptions.Synchronized is equivalent to wrapping the body
of the method in:

lock (this)

or

lock (typeof(TheTypeInvolved))

I wouldn't recommend it, and I wouldn't recommend using "lock this"
anyway.

See http://www.pobox.com/~skeet/csharp/t...ckchoice.shtml for
reasons and recommendations.

Jon

Mar 13 '06 #3
Marc Gravell wrote:
Good article, and the one linked underneath it about an alternative (using)
syntax for Monitor; can I ask a quick question on the latter?

Firstly - the example code includes:

<quote>
// ... or if you want to be able to wait/pulse the monitor
using (LockToken token = syncLock.Lock(10000))
{
Monitor.Wait (token.Monitor);
// or
Monitor.Pulse (token.Monitor);
}
</quote>

First - looking at the code, I think this is a typo of syncLock.Monitor
Yup - things unfortunately changed in the API and I didn't catch them
all in the docs.
In fact, those docs don't do it justice now. If you look at
http://www.pobox.com/~skeet/csharp/m...e/locking.html
there's much more information, including deadlock detecting locks.
but my real question is: why make the monitor publicly visible at all? Why not
just have a SyncLock.Wait, SyncLock.Pulse and SyncLock.PulseAll (or better
still: LockToken.{Wait|Pulse|PulseAll}, since we really should own the lock
before calling these methods) that forwards via System.Threading.Monitor -
this would avoid callers having to mix implementations
(System.Threading.Monitor for some things, SyncLock / LockToken for others).
Also the SyncLock.monitor (field) could possibly be readonly (maybe it's
just my habit, but I tend to make my lock-objects readonly so I don't
accidentally break them by switching values - I'm sometimes clumsy that
way).
The problem is that I can't guarantee to expose *all* the methods of
Monitor, because in some future version it might gain some methods
which I won't know about, and can't add in without breaking its
compatibility with current versions. There's a bit more about this on
the page referred to above. As I say there, I'm willing to
reconsider...
In case tone doesn't carry in an e-mail, I don't mean for this to sound
negative in any way - I think it's a very neat implementation : just some
thoughts and questions.


No, that's fine :)

Jon

Mar 13 '06 #4
That fills in some blanks - thank you.

Marc

"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:11**********************@j33g2000cwa.googlegr oups.com...
Marc Gravell wrote:
Good article, and the one linked underneath it about an alternative
(using)
syntax for Monitor; can I ask a quick question on the latter?

Firstly - the example code includes:

<quote>
// ... or if you want to be able to wait/pulse the monitor
using (LockToken token = syncLock.Lock(10000))
{
Monitor.Wait (token.Monitor);
// or
Monitor.Pulse (token.Monitor);
}
</quote>

First - looking at the code, I think this is a typo of syncLock.Monitor


Yup - things unfortunately changed in the API and I didn't catch them
all in the docs.
In fact, those docs don't do it justice now. If you look at
http://www.pobox.com/~skeet/csharp/m...e/locking.html
there's much more information, including deadlock detecting locks.
but my real question is: why make the monitor publicly visible at all?
Why not
just have a SyncLock.Wait, SyncLock.Pulse and SyncLock.PulseAll (or
better
still: LockToken.{Wait|Pulse|PulseAll}, since we really should own the
lock
before calling these methods) that forwards via
System.Threading.Monitor -
this would avoid callers having to mix implementations
(System.Threading.Monitor for some things, SyncLock / LockToken for
others).
Also the SyncLock.monitor (field) could possibly be readonly (maybe it's
just my habit, but I tend to make my lock-objects readonly so I don't
accidentally break them by switching values - I'm sometimes clumsy that
way).


The problem is that I can't guarantee to expose *all* the methods of
Monitor, because in some future version it might gain some methods
which I won't know about, and can't add in without breaking its
compatibility with current versions. There's a bit more about this on
the page referred to above. As I say there, I'm willing to
reconsider...
In case tone doesn't carry in an e-mail, I don't mean for this to sound
negative in any way - I think it's a very neat implementation : just some
thoughts and questions.


No, that's fine :)

Jon

Mar 13 '06 #5
Hi again; I'm a convert... kind-of...

I toyed with this on the train, and agree that not only is it a nicer
wrapper around lock, but it offers significant development gain (such as the
named locks, which are invaluable). With some changes (see below) I was able
to use this to successfully identify a deadlock issue (in a highly-threaded
system) that has been bugging me for a while:

Some more feedback, however, on the knife-edge call about Pulse, Wait etc;
to assist my debugging, I pushed these methods (as private internal virtual)
onto SyncLock, and forwarded them (as public) from LockToken; this allowed
me to put in some #if DEBUG regions around Lock, Unlock, Wait and Pulse
which keep track of the thread currently holding the lock (in a Thread field
that is likewise #if DEBUG). By doing this, when a timeout occurs I can
include verbose information about exactly which 2 threads are competing. A
bit similar to some of OrderedLock, but my code wouldn't lend itself to an
OrderedLock implementation (without significant rework), where-as with
SyncLock it is an issue. As a side-benefit, it would also allow java-like
"do I hold the lock, else who" calls, but I'm not sure it is worth the
overhead except in DEBUG mode.

Re your thoughts about extensions to Monitor; while I see your point, if
additional functionality is added to Monitor that can't be added to
SyncLock, then a: I'd be suprised (as it would be an equal pain to use in
*any* code - perhaps more as not encapsulated), and b: as a class to do a
specific job, it works very well - so if something *couldn't* be
retro-fitted to SyncLock, then it is probably so esoteric that it wouldn't
want to be.

So, erm, yes; my /personal/ opinion is that this fits a lot better with
Pulse etc on the LockToken, as not only does it allow for a complete locking
solution (encapsulated in one consistent place), but it allows for positive
(debugging) benefit along the way.

(If you want any of my hacks, let me know and I'll e-mail them - but they're
pretty simple to be honest).

Cheers again for (indirectly, but crucially) helping me fix my [dead]locking
woes ;-p

Marc
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:11**********************@j33g2000cwa.googlegr oups.com...
Marc Gravell wrote:
Good article, and the one linked underneath it about an alternative
(using)
syntax for Monitor; can I ask a quick question on the latter?

Firstly - the example code includes:

<quote>
// ... or if you want to be able to wait/pulse the monitor
using (LockToken token = syncLock.Lock(10000))
{
Monitor.Wait (token.Monitor);
// or
Monitor.Pulse (token.Monitor);
}
</quote>

First - looking at the code, I think this is a typo of syncLock.Monitor


Yup - things unfortunately changed in the API and I didn't catch them
all in the docs.
In fact, those docs don't do it justice now. If you look at
http://www.pobox.com/~skeet/csharp/m...e/locking.html
there's much more information, including deadlock detecting locks.
but my real question is: why make the monitor publicly visible at all?
Why not
just have a SyncLock.Wait, SyncLock.Pulse and SyncLock.PulseAll (or
better
still: LockToken.{Wait|Pulse|PulseAll}, since we really should own the
lock
before calling these methods) that forwards via
System.Threading.Monitor -
this would avoid callers having to mix implementations
(System.Threading.Monitor for some things, SyncLock / LockToken for
others).
Also the SyncLock.monitor (field) could possibly be readonly (maybe it's
just my habit, but I tend to make my lock-objects readonly so I don't
accidentally break them by switching values - I'm sometimes clumsy that
way).


The problem is that I can't guarantee to expose *all* the methods of
Monitor, because in some future version it might gain some methods
which I won't know about, and can't add in without breaking its
compatibility with current versions. There's a bit more about this on
the page referred to above. As I say there, I'm willing to
reconsider...
In case tone doesn't carry in an e-mail, I don't mean for this to sound
negative in any way - I think it's a very neat implementation : just some
thoughts and questions.


No, that's fine :)

Jon

Mar 14 '06 #6
Marc Gravell <ma**@nonesuch.com> wrote:
Hi again; I'm a convert... kind-of...

I toyed with this on the train, and agree that not only is it a nicer
wrapper around lock, but it offers significant development gain (such as the
named locks, which are invaluable). With some changes (see below) I was able
to use this to successfully identify a deadlock issue (in a highly-threaded
system) that has been bugging me for a while:
Excellent. It's nice to see it being used "in the wild" as it were.
Some more feedback, however, on the knife-edge call about Pulse, Wait etc;
to assist my debugging, I pushed these methods (as private internal virtual)
onto SyncLock, and forwarded them (as public) from LockToken; this allowed
me to put in some #if DEBUG regions around Lock, Unlock, Wait and Pulse
which keep track of the thread currently holding the lock (in a Thread field
that is likewise #if DEBUG). By doing this, when a timeout occurs I can
include verbose information about exactly which 2 threads are competing. A
bit similar to some of OrderedLock, but my code wouldn't lend itself to an
OrderedLock implementation (without significant rework), where-as with
SyncLock it is an issue. As a side-benefit, it would also allow java-like
"do I hold the lock, else who" calls, but I'm not sure it is worth the
overhead except in DEBUG mode.
Right. Unfortunately, the way that debug/release builds work, you'd
have to have two different versions of the library available (or build
it alongside your project). It's not a great situation :(
Re your thoughts about extensions to Monitor; while I see your point, if
additional functionality is added to Monitor that can't be added to
SyncLock, then a: I'd be suprised (as it would be an equal pain to use in
*any* code - perhaps more as not encapsulated), and b: as a class to do a
specific job, it works very well - so if something *couldn't* be
retro-fitted to SyncLock, then it is probably so esoteric that it wouldn't
want to be.
The problem is a bit more subtle than that though. Suppose .NET 2.1
adds a new method in Monitor:

1) Until I update the source, no-one can use that new method in
conjunction with SyncLock
2) I can't provide a version which works against 1.1/2.0 *and* 2.1,
which would still have all the appropriate methods. Currently I'm just
building against 1.1, and anyone can use the library for 1.1 or 2.0.
I'd rather not get into the business of building multiple versions.

However, all of this rests on Monitor adding methods. I'm tempted to
take the risk...

So, erm, yes; my /personal/ opinion is that this fits a lot better with
Pulse etc on the LockToken, as not only does it allow for a complete locking
solution (encapsulated in one consistent place), but it allows for positive
(debugging) benefit along the way.

(If you want any of my hacks, let me know and I'll e-mail them - but they're
pretty simple to be honest).
If you could mail me the code, it would be handy - I generally find it
easier to understand actual code than descriptions of code :)
Cheers again for (indirectly, but crucially) helping me fix my [dead]locking
woes ;-p


My pleasure - and let me know if you have any more feedback...

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Mar 14 '06 #7

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

Similar topics

2
by: pradyumna | last post by:
In Project settins - C/C++ - Code Generation, what is the difference between the option "Multithreaded" and "Multithreaded DLL". I understand that on selecting multithreaded option, single and...
6
by: Dan Kelley | last post by:
We have a multithreaded app that responds to events, and writes these events to a text file. This text file is used by an external system for further processing. We want to be able to write...
2
by: Rudi | last post by:
Is there anyone who can point me to a good tutorial on how to create a multithreaded class library? Class A is a controller that starts up a number of threads of code in Class B. Class B raises...
1
by: Antal Rutz | last post by:
Hi! I wrote a little class to make multihreading easier. It's based on one of aahz's threading example scripts. What it does: It spawns up number of CollectorThreads and one ProcessThread. The...
7
by: Sidd | last post by:
Hi, I tried finding and example of multithreaded client-serve program in python. Can any one please tell me how to write a multithreaded client-server programn in python such that 1.It can handle...
1
by: Krupa | last post by:
Hi All, I am developing a multithreaded application in c# on vs 2005 (compact framework 2.0). I want to have a socket server in a background thread and want to continue with the windows form...
9
by: bonk | last post by:
Does anyone have a simple example on how to prohibit that any thread other than the current thread modifies a certain object (a collection) while we are in a certain section of the code? In other...
3
by: Jake K | last post by:
I have a multithreaded application that I now want to convert into a Windows Service. Does application.run work in a windows service? Are there things to take into consideration when creating a...
3
by: akmkat | last post by:
Hi all, I am in a great problem. I am trying to implement a multithreaded server using java, first look at the code... /*------- Main Server (server.java)--------------*/ import java.io.* ;...
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: 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
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
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,...
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
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...

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.