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

What does Queue.Synchronized() return

I have a derived class from the Queue base class. I need it to be
thread-safe, so I am using the Synchronized method (among other things out of
scope of this issue). The code below compiles, but at runtime, the cast of
"Queue.Synchronized(new EventQueue())" to an EventQueue object is failing
stating invalid cast.

Why?

public class EventQueue : System.Collections.Queue { ... }

public class AnotherClass {
private static EventQueue q = null;

public void AnotherMethod() {
q = (EventQueue)Queue.Synchronized(new EventQueue());
}
}

Nov 16 '05 #1
6 3699
rmunson8 <rm******@discussions.microsoft.com> wrote:
I have a derived class from the Queue base class. I need it to be
thread-safe, so I am using the Synchronized method (among other things out of
scope of this issue). The code below compiles, but at runtime, the cast of
"Queue.Synchronized(new EventQueue())" to an EventQueue object is failing
stating invalid cast.

Why?


Because although it's returning an instance of Queue, it's not
returning an instance of EventQueue. The returned reference will access
the original EventQueue, but isn't an EventQueue in itself.

Personally I don't like the Synchronized methods anyway, as it
encourages people to reckon they don't have to think about
multi-threading any more (when you still need to place a lock round any
groups of actions which need to happen without interruption).

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

"rmunson8" <rm******@discussions.microsoft.com> wrote in message
news:D7**********************************@microsof t.com...
I have a derived class from the Queue base class. I need it to be
thread-safe, so I am using the Synchronized method (among other things out
of
scope of this issue). The code below compiles, but at runtime, the cast
of
"Queue.Synchronized(new EventQueue())" to an EventQueue object is failing
stating invalid cast.

Why?

public class EventQueue : System.Collections.Queue { ... }

public class AnotherClass {
private static EventQueue q = null;

public void AnotherMethod() {
q = (EventQueue)Queue.Synchronized(new EventQueue());
}
}
It simply returns a synchronized class derived from Queue that wraps the
queue you pass. It does not nessecerily return the same type of queue as you
pass. You will have to write your own implementaion of Synchronized to do
so.

Nov 16 '05 #3
rmunson8 wrote:
I have a derived class from the Queue base class. I need it to be
thread-safe, so I am using the Synchronized method (among other things out of
scope of this issue). The code below compiles, but at runtime, the cast of
"Queue.Synchronized(new EventQueue())" to an EventQueue object is failing
stating invalid cast.

Why?

public class EventQueue : System.Collections.Queue { ... }

public class AnotherClass {
private static EventQueue q = null;

public void AnotherMethod() {
q = (EventQueue)Queue.Synchronized(new EventQueue());
}
}


From what I gather, Queue.Synchronized() returns a
Queue+SynchronizedQueue object wrapper around the Queue passed as the
method parameter. It does not return the same type as the Queue that you
are wrapping.

Either skip the type-casting at the call to Synchronized if you can get
away with using Queue-methods only, or use lock(myQueue.SyncRoot) {} if
you need access to EventQueue specific members.

/Joakim
Nov 16 '05 #4
Thanks. That makes sense. If I take that approach, obviously it is the
responsibility of the user of the object to perform the lock(), however, if I
have overridden several Queue methods in my derived class, would it be a
better design if I locked within those methods or leave this to the user of
the object?

public class EventQueue : System.Collections.Queue
{
public override void Enqueue(object obj)
{
lock (this.SyncRoot)
{
base.Enqueue(obj);
if (this.EventAdded != null)
{
this.EventAdded(this, new EventArgs());
}
}
}

"Jon Skeet [C# MVP]" wrote:
rmunson8 <rm******@discussions.microsoft.com> wrote:
I have a derived class from the Queue base class. I need it to be
thread-safe, so I am using the Synchronized method (among other things out of
scope of this issue). The code below compiles, but at runtime, the cast of
"Queue.Synchronized(new EventQueue())" to an EventQueue object is failing
stating invalid cast.

Why?


Because although it's returning an instance of Queue, it's not
returning an instance of EventQueue. The returned reference will access
the original EventQueue, but isn't an EventQueue in itself.

Personally I don't like the Synchronized methods anyway, as it
encourages people to reckon they don't have to think about
multi-threading any more (when you still need to place a lock round any
groups of actions which need to happen without interruption).

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

Nov 16 '05 #5
rmunson8 <rm******@discussions.microsoft.com> wrote:
Thanks. That makes sense. If I take that approach, obviously it is the
responsibility of the user of the object to perform the lock(), however, if I
have overridden several Queue methods in my derived class, would it be a
better design if I locked within those methods or leave this to the user of
the object?

public class EventQueue : System.Collections.Queue
{
public override void Enqueue(object obj)
{
lock (this.SyncRoot)
{
base.Enqueue(obj);
if (this.EventAdded != null)
{
this.EventAdded(this, new EventArgs());
}
}
}


For a start, don't execute an event within a lock :)

See http://www.pobox.com/~skeet/csharp/t...ckchoice.shtml

I would suggest making it the responsibility of the user to lock
appropriately unless the class is very definitely going to be used for
multi-threading (e.g. it's a producer/consumer queue with one thread
producing items and another thread consuming them).

Letting the user do the locking means you can get best performance for
an application which doesn't use any instance in more than one thread,
while a multi-threaded application will be able to choose its own
locking strategy. Make sure you document your class's thread safety
though.

--
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
Here is example how syncronized queue is implemented. Basically it is a
*very simple wrapper:
internal class SyncQ : Queue
{
private Queue q;
private object syncRoot;

public SyncQ(Queue q)
{
this.q = q;
this.syncRoot = this.q.SyncRoot;
}

public override void Clear()
{
lock(this.syncRoot)
{
this.q.Clear();
}
}

public override object Dequeue()
{
object obj;
lock(syncRoot)
{
obj = this.q.Dequeue();
}
return obj;
}
//And so on...
}

Naturally, you can do this yourself if you need special function. The .Net
sync wrapper should work on any queue that derives from Queue. However, I
agree with Jon and would manually sync myself as you will probably need to
anyway at different points as your complexity grows. Say you want to check
the Count and then Dequeue only if count is > 0. You need to lock SyncRoot
anyway even if using a Sync Wrapper as you want the count test and the
Dequeue operation to be one atomic operation. So in this case, you end up
with three Monitor locks, the manual SyncRoot you do yourself, and the two
locks the SyncWrapper does (one for Count "Get" and one for the Dequeue
method). It is the same Monitor object, but a lock is taken and released
three times. There are others you will run into and others that could
result in even more locks being taken and released. This is one example of
how simple .Net can be, but yet can hurt our perf if we don't consider what
is really happening under the covers. Just some thoughts. Cheers!

--
William Stacey, MVP
http://mvp.support.microsoft.com

"rmunson8" <rm******@discussions.microsoft.com> wrote in message
news:D7**********************************@microsof t.com...
I have a derived class from the Queue base class. I need it to be
thread-safe, so I am using the Synchronized method (among other things out of scope of this issue). The code below compiles, but at runtime, the cast of "Queue.Synchronized(new EventQueue())" to an EventQueue object is failing
stating invalid cast.

Why?

public class EventQueue : System.Collections.Queue { ... }

public class AnotherClass {
private static EventQueue q = null;

public void AnotherMethod() {
q = (EventQueue)Queue.Synchronized(new EventQueue());
}
}


Nov 16 '05 #7

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

Similar topics

4
by: chrisben | last post by:
Hi I often use Queue.Synchronized method to create a queue for multithread writing. I also know I could use SyncRoot and lock to write Queue. Could anyone here please explain to me the pros and...
1
by: Frank Rizzo | last post by:
Some of the classes in the framework are marked as thread-safe in the documentation. In particular the docs say the following: "Any public static (*Shared* in Visual Basic) members of this type...
2
by: Chuck | last post by:
I have not been able to find a good answer about the System.Collections.Queue.Synchronized() method and how it actually works or is to be used. If I create my Queue in the following manner: ...
4
by: Macca | last post by:
Hi, I've been reading the online documentation for the System.Collections.Queue object on how to implement a threadsafe Queue object. I understand the basics, by using the wrapper returned by...
4
by: nhmark64 | last post by:
Hi, Does System.Collections.Generic.Queue not have a Synchronized method because it is already in effect synchronized, or is the Synchronized functionality missing from...
13
by: Jonathan Amsterdam | last post by:
I think there's a slight design flaw in the Queue class that makes it hard to avoid nested monitor deadlock. The problem is that the mutex used by the Queue is not easy to change. You can then...
18
by: cj | last post by:
members of this type are safe for multithreaded operations. Instance members are not guaranteed to be thread-safe. I'm under the impression before you can use a class you have to make an...
1
by: =?Utf-8?B?ZnJtZGV2ZWxvcGVy?= | last post by:
I'm porting an application from a Unix like system to Windows. I'm looking for a simple queue with FIFO characteristics which will cause the calling thread to suspend if there is no data on the...
19
by: =?ISO-8859-1?Q?Nordl=F6w?= | last post by:
I am currently designing a synchronized queue used to communicate between threads. Is the code given below a good solution? Am I using mutex lock/unlock more than needed? Are there any resources...
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
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
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
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...
0
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...

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.