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

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

C# Thread Safe Class events

Posted By:      Posted Date: September 02, 2010    Points: 0   Category :.NET Framework
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

View Complete Post

More Related Resource Links

Basic Instincts: Programming Events of the Framework Class Libraries


Some practical examples of handling some of the more commonly used events in the Microsoft .NET Framework.

Ted Pattison

MSDN Magazine May 2003

.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

ThreadPool with lock isn't thread safe

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));

Raising events of base class


I have base class with public event:

public abstract class MessageProcessor
        public event EventHandler<MessageEventArgs> MessageReceived;


And I want to raise this event from derived class:

public class Device:MessageProcessor

        void timerAlive_Elapsed(object sender, ElapsedEventArgs e)
            MessageReceived(this, null); //compilation-time error here



Error :The event 'WorkServerClasses.MessageProcessor.MessageReceived' can only appear on the left hand side of += or -= (except when used from within the type 'WorkServerClasses.MessageProcessor')

How can I resolve this?

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?


Session in a Class in a Thread



I'm starting a new thread with:

Dim Thread_Connect As New Threading.Thread(AddressOf Thread_ConnectCustomerToDebitor)


In the thread I can acces the session values with:


But i need the session values in a class. There i got the error "Session is not declared". Usually i can access the session with:


But in the new thread is HttpContext.Current=Nothing

How can I access the session values inside the class?

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


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 ?








Handling API events in a background thread



I am in the planning stages for developing a VB.Net class (I am using VS 2008) that is to obtain data via an API provided by a COM object (AxInterop.TWSLib) making requests to an Internet server. The API provides data via events. The class should do its work on a separate thread; it takes several seconds (sometimes up to ~10) to collect the desired data. One should be able to instantiate several instances of the class in order to collect data in parallel. The class would be given a reference to the TWSLib object when its constructor is called, as well as several parameters. There needs to be a way for the class to provide results, preferably in the form of a generic list.

I have succeeded creating multithreads using the backgroundworker approach. From what I have read, though, that does not appear to be the appropriate approach when the background thread is supposed to wait for events to handle. I have not tackled more advanced multithreading approaches. Studying VS 2008 documentation on Threading, ThreadPool, delegates, etc. has not yet given me an idea how to design a class that handles those API event

Events not being fired from client class


Hello! I will try to keep this as short and concise as possible.

I am working on a client-server application. Everything worked well, the client (which consisted of a form at that time) got the events from the server, but the problem was that I was doing everything in the form class. So I thought that it would be nicer to create a 'Client' class which the form would use. All the code would go in the Client class and the form class would just call one or two methods.

Now, my Client class gets the events from the server, does something with the data, and fires its own events which should be picked up by the form class, but that doesn`t happen. I experimented a bit, trying to fire events from different classes, changed some code here and there and came to the conclusion that if my Client class inherits from Control, the form class will pick up the events fired from the Client class.My questions is the following: what exactly should i add to my Client class (the necessary minimum) in order for the events to work properly? Inheriting from Control just to make the events work seems a bit too much.

Edit: I tracked it down and the 'most base' class that I have to inherit from is MarshalByRefObj. Is this always necessary in cases such as mine? And if yes, why? 

Class Diagrams

Class diagrams show the static structure of the systems. Classes define the properties of the objects which belong to them. These include:

Attributes - (second container) the data properties of the classes including type, default value and constraints.

WCF Tutorial - Events and Callbacks

we described how to make a very simple client/server application where clients would call functions on the server through a shared interface. In this tutorial, I'm going to expand that application to allow the server to execute functions on the client by using callbacks. Essentially, this is WCF's mechanism to allow events to be raised from the server to it's connected clients.

Creating a Simple Class in C#

The second article in the C# Object-Oriented Programming tutorial describes how classes are created in C# and how behaviour, in the form of publicly visible and private, hidden methods can be added. This demonstrates some of the uses of encapsulation
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