.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal
Post New Web Links

ThreadPool with lock isn't thread safe

Posted By:      Posted Date: August 30, 2010    Points: 0   Category :.NET Framework
Hello, I'm having some problems with my code which apparently isn't thread safe at all. The problem is that it doesn't crash often, but of course it does when in production! I have twisted my mind around the problem for a month or so now, and I need some help in sorting out the problem. Well, the problem is that it isn't thread safe, and the collection (_subscribers) is modified while looping. The error says that it crashes in the method: SendRoundSettings. Here's part of the code (which I guess contains the error, as the other methods are pretty much identical): [ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple)] public class DuplexService : IDuplexService { private readonly object _syncRoot = new object(); private static Subscribers _subscribers = new Subscribers(); private static RoundSettings _currentRoundSettings = new RoundSettings() {CompetitionId = 1, NumberOfAthletesInRound = 0, Round = 0, SortDirection = SortDirection.ByStartNumber}; public void SendJudgeScore(CompetitionJudgeAthleteJump judgeScore) { ThreadPool.QueueUserWorkItem(state => { Subscribers clonedSubscribers = CloneSubscribers(); Console.WriteLine("Sending judgeScore to {0} client(s)", clonedSubscribers.Count(x => x.CompetitionId == judgeScore.CompetitionId));

View Complete Post

More Related Resource Links

Concurrent Affairs: Build a Richer Thread Synchronization Lock


In my last column, I showed the various thread synchronization mechanisms employed by the Microsoft® . NET Framework (see Concurrent Affairs: Performance-Conscious Thread Synchronization). I then examined the performance characteristics of all these mechanisms and determined that the Interlocked methods performed the best because the calling thread never has to transition to kernel mode.

Jeffrey Richter

MSDN Magazine March 2006

.NET Column: Safe Thread Synchronization


By far, the most common use of thread synchronization is to ensure mutually exclusive access to a shared resource by multiple threads. In the Win32® API, the CRITICAL_SECTION structure and associated functions offers the fastest and most efficient way to synchronize threads for mutually exclusive access when the threads are all running in a single process.

Jeffrey Richter

MSDN Magazine January 2003

C# Thread Safe Class events

Right now I have created a custom base class that has numerous events.  These events have non-standard signatures and are fired from a thread I have that is basically just a while loop checking variables against older ones for telling when something has changed. As far as I know this is the best way to go about doing this is to just make a void on another thread in a while (true) loop, in the loop just doing ifs... than doing a thread sleep.  I make sure the thread is a background thread that way it'll exit propertly when the consumer exits.  If anyone knows a beter way of going about this than stop reading here. :) If not that onto my real question... I have events that are fired from this loop on the thread I created, now they're attatched on the consumer app and no matter what I do I can't seem to get these events to be thread-safe so that I don't have to use the Control.Invoke method for each event. If anyone knows anything that'll help me out it'll be much appreciated. Thanks,Chad

Are non-static objects thread-safe in a static-method?


I am using javascript and ajax to call server side mothod.  The pagemethod can only be static function in teh server side.  But i know static methods are not thread safe across simultaneous sessions.  However, what if the static method is modifying a non-static object?

for example:

public partial class default : system.web.ui.page

Hero Superman; // create an object called superman of class hero for all user sessions independently

public static int(newpowers)


Superman.powers = newpowers;  // Is this thread safe?  Will each user not accidentally get written by another user's power values?


web service thread-safe?



I am using a COPY web service. Is the function that uploads a document, COPYINTOITEMS, a thread-safe? If not, what is a good way to do a similar thing?

I am thinking to create one copy object and all incoming requests(thread) share this object to invoke CopyIntoItems function.

Thank you.

Is Dispatcher.BeginInvoke really NOT thread safe, while the old System.Windows.Forms.Control.BeginIn




System.Windows.Forms.Control.BeginInvoke is documented as thread safe (in fact, BeginInvoke , EndInvoke , Invoke , InvokeRequired , and CreateGraphics are).



But in WPF, Dispatcher.BeginInvoke is not documented as thread safe. Which would appear to me as a regression (and not really convenient, to be honest).

Was it only forgotten in MSDN documentation, or should I really use external locking to prevent the dispatcher to get lost in its messages and priorities?



Thanks. ;)

Is XpathDocument thread safe?!? (FileShare.Read access?)


if you  have a private void function inside of main page of system.web.page.ui

            XPathNavigator nav;
            XPathDocument docNav;
            XPathNodeIterator NodeIter;
            docNav = new XPathDocument(@"D:\data\data.xml");
            nav = docNav.CreateNavigator();

and multiple users are now on the web application simultaneously using nav object, will it be thread safe?  In filestream, the solution was to use FileShare.Read parameter.  but does xpathdocument have something similar?


Writing to log file on first pageload (!ispostback). thread safe


Based on this piece of code, I want to do exactly like this demonstration.  However, correct me if I'm wrong but if two or more users somehow simultaneously access the web page at the same precise nanosecond in time, then wouldn't we have a race condition?  So is this piece of code valid?  How would I correct this to make it thread safe???

If you like to support this site, feel free to make a donation to support improvements.

Thank you!
Monetize Your Blog

How to track visitors to your site in ASP.NET & C#
Code to log the IP address & DNS name for visitors to each page
Posted on 4/3/2007 1:52:07 PM in #ASP.NET
[lnkImage] [lnkImage] [lnkImage] [lnkImage] [lnkImage] [lnkImage] [lnkImage] [lnkImage] [lnkImage] [lnkImage] [lnkImage] [lnkImage]   ASP.NET Social Bar? Get A Free one here!

Once you have published a site in ASP.NET, you'd like to know who are your visitors. One way is to check your event log on the host server. Another option is to write your own code. You'd basically like to log the IP address, and DNS name for the visitor, and it would be nice to know which page they are visiting.

To log the ip address using ASP.NET, you can call:


Another usefull variable is


Adding rows to a databound DataSet/DataTable from a ThreadPool thread does not update UI


I have an WPF .NET 4.0 application which creates a TreeView in the main thread, and databinds it to a DataSet which contains two DataTables. The datatables have a simple relationship between them which represents a two-level tree. When the treeview is initially drawn, it correctly displays all items from the two datatables as a two level tree.

When the DataTables are updated from the UI thread (add/delete/modify a row), the treeview is refreshed and the changes to the databound DataSet DataTables are visible in the treeview.

If changes to the DataTables are made from a ThreadPool thread, no exceptions are thrown, but the UI is not updated. I am using a threadpool thread because the changes will be initiated from multiple network devices and processing their data is fairly CPU intensive.

I am assuming that change notifications are not being propogated across threads for DataSets/DataTables.  Is this assumption correct? If so, are their recommended best practices to overcome this limitation?

ChannelFactory / thread safe?


Is ChannelFactory<T>.CreateChannel thread safe in .NET 4.0?  Would like to use as a singleton dependency via castle windsor.





Is AcceptAsync on Socket is Thread Safe?


Hi ,


I am using the Asynchronous methods of the Socket class to Socket Communication. I would like to know whether the Usage of AcceptAsync is thread safe , ie I need to handle large number of connections at a time and cannot spend much time in handling a connection , hence  I am calling AcceptAsync in a loop initially (say 100 iterations ) using differnt SocketAsyncArgs Object,

and in the Event handler for SocketSyncEventRgs Completed Event , I am queing the just established connection to a threadpool thread for further execution (by passing the AcceptSocket of the SocketAsuncArgs)and then again calls AcceptAsync  on the main socket with a new SocketAsyncEventArgs object .

ie Intial AcceptAsync in  a loop and each time a connection established just after queing that connection to another threadpool thread, again calling AcceptAsync on the Main listening socket , So there is a chance that multiple threads will call AcceptAsync on the same Main Listening Socket and but with different SocketAsyncArgs Object , Is there any risk in this ?








Thread Performance: Resource Contention Concurrency Profiling in Visual Studio 2010


Visual Studio 2010 includes new resource contention profiling features that help detect concurrency contention among threads. We walk through a profiling investigation to demonstrate how you can pinpoint and fix resource contention problems in your code.

Maxim Goldin

MSDN Magazine June 2010

Thread Diagnostics: Performance Tuning with The Concurrency Visualizer in Visual Studio 2010


Understanding performance bottlenecks in multithreaded apps used to require significant instrumentation and analysis by expert developers. The Concurrency Visualizer in Visual Studio 2010 significantly reduces the burden of parallel performance analysis.

Hazim Shafi

MSDN Magazine March 2010

.NET Matters: Ordered Execution With ThreadPool


This month we demonstrate how you can use the ThreadPool to support ordered execution without having to build custom thread pools yourself.

Stephen Toub

MSDN Magazine February 2009

Net Matters: Round-Robin Access To The ThreadPool


Stephen Toub shows you how to add round-robin scheduling support on top of the ThreadPool for more granular processing control.

Stephen Toub

MSDN Magazine January 2009

CLR Inside Out: Thread Management In The CLR


Getting the performance you want in concurrent applications is not as straightforward as you might think. See how common threading issues can affect your application.

Erika Fuentes and Eric Eilebrecht

MSDN Magazine December 2008

Editor's Note: new Thread(ReadEditorsNote).Start(); yourAttention.WaitOne();


Introducing the issue, Howard Dierking points out that you can't simply parallelize your code blindly if you expect to truly reap the benefits that parallelism promises.

Howard Dierking

MSDN Magazine October 2008

ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend