473,786 Members | 2,775 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

thread-safe use of .NET events/delegates? How?

I'm trying to figure out how to safely use .NET events/delegates in a
thread-safe class. There are a couple problems. One is that the standard
"if(EventNa me != null) EventName(...); " call can fail if the event is
emptied of all methods between the two statements, implying that some sort
of synchronization between this and removals from EventName is needed. The
other problem is that if an event with a set of delegates is in the process
of being called, and you remove a method from the set, that method might
still get called one last time _after_ you removed it, as you can't modify
the executing delegate (they're immutable, so the removal creates a new one
with that method removed). That creates a bit of a problem if I've disposed
an object, it's removed itself from an event hook, then later gets called
via the removed event hook again. Ick.

A partial solution I thought of is to try synchronizing access to the event
calling method and removals from the event delegate. It's only a partial
solution, as methods called by the event could cause a removal from the
event (because they're called from within the synchronization ), and the
latter problem would be exhibited again.

There must be a Right Way to handle this, as I'm sure folks have written
thread-safe classes that use .NET events/delegates. I just can't find any
examples or documentation about this. Can anyone help? Is there a design
pattern / standard for this that doesn't involve screwing up the semantics
of .NET events?
I've put up two test cases for the problems I mentioned here:
http://www-cse.ucsd.edu/~sbrown/oddities/ . I've also included a more
formal description of the problems and an example class that would exhibit
them below (also at that link):

using System;
using System.Threadin g;

// This is a basic example of trying to use .NET events in thread-safe
classes.
// There are a couple problems in this class:
//
// 1. There is a race between checking SomeEvent != null and calling
SomeEvent.
// If all methods are removed from SomeEvent between those points, an
exception
// is thrown.
//
// 2. There is a race when calling SomeEvent and removing a method from
// SomeEvent. Since delegates are immutable, removing a method from the
event
// during a call of the delegate will not stop that method from being
called;
// it could still get called one last time even after being removed if it
// hadn't yet been called by the executing delegate.
//
//
// Problem #1 is common to any class that claims to be thread-safe and uses
// events.
//
// Problem #2 seems common to the .NET framework and as such probably must
be
// handled by the receiver somehow.
//
// I've yet to see examples of how either problem is supposed to be
addressed.
// I desperately need said examples.
//
//
// Syncrhonization could be used between OnSomeEvent and modifications to
// SomeEvent to partially address the problems, but problem #2 would still
// exist for methods called by SomeEvent, since they would be called from
// within the syncrhonization . It feels like the receiver must be the one
to
// address problem #2, not the sender.
public class SomethingThatCr eatesEvents : IDisposable {
private Thread thread;

public SomethingThatCr eatesEvents() {
thread = new Thread(new ThreadStart(Eve ntDispatcher));
thread.Start();
}

private void EventDispatcher () {
while(!disposed ) {
OnSomeEvent();
}
}

public event EventHandler SomeEvent;
protected virtual void OnSomeEvent() {
if(SomeEvent != null) {
SomeEvent(this, new EventArgs());
}
}

private bool disposed = false;
public void Dispose() {
if(!disposed) {
disposed = true;
thread.Join();
}
}
}
Nov 22 '05 #1
0 4206

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

Similar topics

14
2181
by: adeger | last post by:
Having trouble with my first forays into threads. Basically, the threads don't seem to be working in parallel (or you might say are blocking). I've boiled my problems to the following short code block and ensuing output. Seems like the output should be all interleaved and of course it's not. Running Python 2.2 from ActiveState on Windows XP (also doesn't work on Windows 2000). Thanks in advance! adeger
4
2897
by: Gilles Leblanc | last post by:
Hi I have started a small project with PyOpenGL. I am wondering what are the options for a GUI. So far I checked PyUI but it has some problems with 3d rendering outside the Windows platform. I know of WxPython but I don't know if I can create a WxPython window, use gl rendering code in it and then put widgets on top of that...
7
2705
by: Ivan | last post by:
Hi I have following problem: I'm creating two threads who are performing some tasks. When one thread finished I would like to restart her again (e.g. new job). Following example demonstrates that. Problem is that when program is started many threads are created (see output section), when only two should be running at any time. Can you please help me to identify me where the problem is? Best regards
5
2830
by: Razzie | last post by:
Hi all, A question from someone on a website got me thinking about this, and I wondered if anyone could explain this. A System.Threading.Timer object is garbage collected if it has no references to it. But what about threads? If I start a new thread that only does 1+1, is it garbage collected after that? If so, do all threads get garbage collected eventually that are 'done'? And if not, why not? Are there references to the thread that...
16
3313
by: droopytoon | last post by:
Hi, I start a new thread (previous one was "thread timing") because I have isolated my problem. It has nothing to do with calling unmanaged C++ code (I removed it in a test application). I have a thread "_itTaskThread" running. The application is listening on a TCP port. It accepts 2 connection from a client. I simulate a crash on the client side (using "Debug->StopDebugging").
9
3078
by: mareal | last post by:
I have noticed how the thread I created just stops running. I have added several exceptions to the thread System.Threading.SynchronizationLockException System.Threading.ThreadAbortException System.Threading.ThreadInterruptedException System.Threading.ThreadStateException to see if I could get more information about why the thread stops running but that code is never executed. Any ideas on how I can debug this?
7
2695
by: Charles Law | last post by:
My first thought was to call WorkerThread.Suspend but the help cautions against this (for good reason) because the caller has no control over where the thread actually stops, and it might have a lock pending, for example. I want to be able to stop a thread temporarily, and then optionally resume it or stop it for good.
4
6221
by: jayesah | last post by:
Hi All, I am writting a Thread class with using pthread library. I have some problem in saving thread function type and argument type. How to make Thread class generic ? /* This is my global Function */ template < class FunType, class ArgType> Thread makeThread(Funtype fun, ArgType arg)
6
5129
by: HolyShea | last post by:
All, Not sure if this is possible or not - I've created a class which performs an asynchronous operation and provides notification when the operation is complete. I'd like the notification to be performed on the same thread thread that instantiated the class. One way to do this is to pass an ISynchronizeInvoke into the class and use it to synchronize the callback. In the constructor of the class, could I take note of the current thread...
3
35406
by: John Nagle | last post by:
There's no way to set thread priorities within Python, is there? We have some threads that go compute-bound, and would like to reduce their priority slightly so the other operations, like accessing the database and servicing queries, aren't slowed as much. John Nagle
0
9497
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10363
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10164
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9962
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8992
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6748
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5398
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3670
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2894
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.