score:4
the call to enqueue
and the call to dequeue
are thread safe.
however, your sample code is not:
between the call to enqueue
and the call to dequeue
there could have been a thread switch. this means, that item
might be another instance than obj
or the call to dequeue
throws an exception, because it now is empty.
to make your sample code thread safe, you still need to lock explicitly:
lock(_item.syncroot)
{
_item.enqueue(obj);
var item = _item.dequeue);
}
only now it is guaranteed, that item
reference-equals obj
in all circumstances.
score:2
from msdn
to guarantee the thread safety of the queue, all operations must be done through this wrapper only.
enumerating through a collection is intrinsically not a thread-safe procedure. even when a collection is synchronized, other threads can still modify the collection, which causes the enumerator to throw an exception. to guarantee thread safety during enumeration, you can either lock the collection during the entire enumeration or catch the exceptions resulting from changes made by other threads.
just as john skeet's answer suggests here, you might be better or using locking since enumerating might cause an exception.
gregs answer also talks about what marc mentions with the count
not being thread safe.
score:4
that is pretty much what synchronizedqueue
does, but there is a problem... typically you need to check the .count
and .dequeue()
in one atomic unit - not check the .count
(one unit) then .dequeue()
(another unit) - you can't trust .count
at all once the lock is surrendered, and .dequeue()
will throw if another thread has stolen the work.
maybe try concurrentqueue<t>
in 4.0 (with .trydequeue()
), or use queue<t>
and lock
.
Source: stackoverflow.com
Related Query
- Async Void, ASP.Net, and Count of Outstanding Operations
- Painfully slow Azure table insert and delete batch operations
- How do Prefix (++x) and Postfix (x++) operations work?
- System.ObjectDisposedException: The ObjectContext instance has been disposed and can no longer be used for operations that require a connection
- Azure Functions: Queue Trigger is expecting Base-64 messages and doesn't process them correctly
- Decimal and mathematical operations
- Observable Stack and Queue
- Stack and Queue enumeration order
- Why volatile and MemoryBarrier do not prevent operations reordering?
- How to add an IEumerable Collection to a Queue and Process each item asynchronously in .NET?
- Large Object Heap and String Objects coming from a queue
- how do you implement Async Operations in C# and MVVM?
- What data structure or mix of data structures would I use for a concurrent queue that allows for bulk and specific deletes?
- .NET question about asynchronous socket operations and message framing
- Min and Max operations on enum values
- Connecting to remote queue manager using C# and .Net
- How would I implement a QueueDictionary, a combination of Queue and Dictionary in C#?
- Standard Operations on Option<T> monad beyond Bind and Map
- MVC 3 - The ObjectContext instance has been disposed and can no longer be used for operations that require a connection
- Why doesn't Stack, Queue and List shrink the internal array after removing an item?
- Command pattern and asynchronous operations handling in C#
- Ensure a long running task is only fired once and subsequent request are queued but with only one entry in the queue
- How to design unit of work to support bulk operations and give more performance?
- TFS 2010 API: Queue builds synchronously and get the state of each queued build: "Run On Agent (waiting for build agent)"
- swagger.json paths and definitions are empty. No operations defined in spec
- Difference Between Actor model and web service/Message Queue
- What is the difference between String and string in C#?
- How do I create an Excel (.XLS and .XLSX) file in C# without installing Microsoft Office?
- What is a NullReferenceException, and how do I fix it?
- AddTransient, AddScoped and AddSingleton Services Differences
More Query from same tag
- Download text as file in ASP.NET
- C# List<Stream> dispose/close
- Release COM Components
- How do you use an existing variable within one or more for loops?
- StyleCop Rule for Multiline Curly Brackets
- Copy text from word file to a new word
- Creating a newline in rich text box
- Which .NET Memcached client do you use, EnyimMemcached vs. BeITMemcached?
- Casting entire array of objects to string
- Converting Json.Net JValue to int
- Object oriented n-tier design. Am I abstracting too much? Or not enough?
- Replace German characters (umlauts, accents) with english equivalents
- How to get environment variables from inside Main() in ASP.NET Core?
- How to control which order the EF Core run custom migrations?
- How to Pass Bool (BIT) parameter to SQL server?
- WebClient DownloadFile - Access denied or could not find part of the path
- Application.Restart not passing arguments back
- How to add a xml in web.config?
- Int numbers appearing as 0x00000000
- Convert.DateTime throws error: String was not recognized as a valid DateTime for "06-13-2012"
- Why does System.Net.Sockets.Socket.AcceptAsync complete with ConnectionReset after a long time of inactivity?
- Hangfire not running tasks although they are in database
- Combine two (or more) PDF's
- Parameter validation in "async"/"await" methods should be wrapped
- How to delete selected rows from a DataGridView?
- Can't enter enter text in TextBox control inside Flyout
- Implement Prism in existing Xamarin.Forms Shared Application
- How to calculate/profile percentage of parallelized C# Code
- What is the purpose of using CommandType.Tabledirect?
- Does C# have an Unsigned Double?