473,406 Members | 2,954 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,406 software developers and data experts.

Multithreaded multicasting and multihandling

If I subscribe multiple event handlers to an event, then they are called
sequentially, right? Is there a native way to have them invoked
simultaneously in separate threads, or would I have to build that
functionality myself? (I don't want to reinvent the wheel here.)

MORE IMPORTANTLY: Is there any legitimate way to connect a single event
handler instance to multiple event generators running in separate threads?
If so, how is synchronization handled within the event handler object?

Apr 25 '06 #1
6 2593
Dave Booker <db******@newsgroup.nospam> wrote:
If I subscribe multiple event handlers to an event, then they are called
sequentially, right? Is there a native way to have them invoked
simultaneously in separate threads, or would I have to build that
functionality myself? (I don't want to reinvent the wheel here.)
You'd have to build it yourself.
MORE IMPORTANTLY: Is there any legitimate way to connect a single event
handler instance to multiple event generators running in separate threads?
Assuming the events are thread-safe in terms of subscription and
execution, and your event handler is thread-safe in execution,
everything should be fine.
If so, how is synchronization handled within the event handler object?


It's not really - by default the event handler will be called in
whatever thread raises the event.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Apr 25 '06 #2
| If I subscribe multiple event handlers to an event, then they are called
| sequentially, right? Is there a native way to have them invoked
| simultaneously in separate threads, or would I have to build that
| functionality myself? (I don't want to reinvent the wheel here.)

TMK, you need to do that yourself. I might just start them on the
threadpool unless you really need all delegates to run on seperate threads,
then you need to create the new threads yourself.

| MORE IMPORTANTLY: Is there any legitimate way to connect a single event
| handler instance to multiple event generators running in separate threads?
| If so, how is synchronization handled within the event handler object?

Not sure I understand.
Apr 25 '06 #3
Dave Booker <db******@newsgroup.nospam> wrote:
If I subscribe multiple event handlers to an event, then they are called
sequentially, right? Is there a native way to have them invoked
simultaneously in separate threads, or would I have to build that
functionality myself? (I don't want to reinvent the wheel here.)
You'd have to do it yourself. It's fairly easy with
ThreadPool.QueueUserWorkItem() and anonymous delegates.

---8<---
using System;
using System.Threading;

class App
{
delegate void SomeEvent();

static SomeEvent CreateHandler(TimeSpan delay)
{
return delegate
{
Thread.Sleep(delay);
Console.WriteLine("Hello from {0} (delay {1}).",
Thread.CurrentThread.ManagedThreadId,
delay);
};
}

static event SomeEvent _someHandler;

static void Main()
{
// Create some handlers with decreasing delays, so first
// will have largest delay, and later have smaller delays.
for (int i = 1000; i >= 500; i -= 100)
_someHandler +=
CreateHandler(TimeSpan.FromMilliseconds(i));

Console.WriteLine("Calling delegates on this thread...");
foreach (SomeEvent e in _someHandler.GetInvocationList())
e();

Console.WriteLine("Calling delegates in background...");
foreach (SomeEvent e in _someHandler.GetInvocationList())
{
SomeEvent f = e;
ThreadPool.QueueUserWorkItem(delegate { f(); });
}

// Readline to wait for threadpool to finish.
Console.ReadLine();
}
}
--->8---
MORE IMPORTANTLY: Is there any legitimate way to connect a single event
handler instance to multiple event generators running in separate threads?
If so, how is synchronization handled within the event handler object?


It's not thread-safe. The += operator on events which don't have explicit
an add and remove is simply a method call to a method called
add_<yourEventNameHere>, with a body which performs += on the delegate
behind the event. The += operator for delegates is implemented with
Delegate.Combine:

---8<---
myDelegate += MyMethod;
--->8---

Translates roughly to:

---8<---
myDelegate = (MyDelegateType)
Delegate.Combine(myDelegate, new MyDelegateType(MyMethod));
--->8---

As you can see, there's a race condition there for reads on myDelegate. So
you need synchronization to safely set the delegate, and thus the event.

Don't forget that you can use 'add' and 'remove' (similar to 'get' and
'set' for properties) on the event declaration to add implicit locking if
you want.

-- Barry
Apr 25 '06 #4
If I subscribe multiple event handlers to an event, then they are called
sequentially, right? Is there a native way to have them invoked
simultaneously in separate threads, or would I have to build that
functionality myself? (I don't want to reinvent the wheel here.)
You'd have to do it yourself. It's fairly easy with
ThreadPool.QueueUserWorkItem() and anonymous delegates.

---8<---
using System;
using System.Threading;

class App
{
delegate void SomeEvent();

static SomeEvent CreateHandler(TimeSpan delay)
{
return delegate
{
Thread.Sleep(delay);
Console.WriteLine("Hello from {0} (delay {1}).",
Thread.CurrentThread.ManagedThreadId,
delay);
};
}

static event SomeEvent _someHandler;

static void Main()
{
// Create some handlers with decreasing delays, so first
// will have largest delay, and later have smaller delays.
for (int i = 1000; i >= 500; i -= 100)
_someHandler +=
CreateHandler(TimeSpan.FromMilliseconds(i));

Console.WriteLine("Calling delegates on this thread...");
foreach (SomeEvent e in _someHandler.GetInvocationList())
e();

Console.WriteLine("Calling delegates in background...");
foreach (SomeEvent e in _someHandler.GetInvocationList())
{
SomeEvent f = e;
ThreadPool.QueueUserWorkItem(delegate { f(); });
}

// Readline to wait for threadpool to finish.
Console.ReadLine();
}
}
--->8---
MORE IMPORTANTLY: Is there any legitimate way to connect a single event
handler instance to multiple event generators running in separate threads?
If so, how is synchronization handled within the event handler object?


It's not thread-safe. The += operator on events which don't have explicit
an add and remove is simply a method call to a method called
add_<yourEventNameHere>, with a body which performs += on the delegate
behind the event. The += operator for delegates is implemented with
Delegate.Combine:

---8<---
myDelegate += MyMethod;
--->8---

Translates roughly to:

---8<---
myDelegate = (MyDelegateType)
Delegate.Combine(myDelegate, new MyDelegateType(MyMethod));
--->8---

As you can see, there's a race condition there for reads on myDelegate. So
you need synchronization to safely set the delegate, and thus the event.

Don't forget that you can use 'add' and 'remove' (similar to 'get' and
'set' for properties) on the event declaration to add implicit locking if
you want.

-- Barry
Apr 25 '06 #5
Barry Kelly <ba***********@gmail.com> wrote:
MORE IMPORTANTLY: Is there any legitimate way to connect a single event
handler instance to multiple event generators running in separate threads?
If so, how is synchronization handled within the event handler object?
It's not thread-safe. The += operator on events which don't have explicit
an add and remove is simply a method call to a method called
add_<yourEventNameHere>, with a body which performs += on the delegate
behind the event.


Not true - a field-like event will lock on *something*, according to
the C# spec. In 1.1, it would always be "this" or
typeof(TheTypeInvolved); in 2.0 it can be a hidden object if the
compiler so desires.

(The MS compiler still just makes the add_XXX method synchronized as
far as I've seen; i.e. it locks on "this" or the type.)

How the event is fired is also part of the thread safety aspect - care
is needed to make sure that the most up-to-date version is used, and
that's it's used without the risk of a NullReferenceException, and
without keeping a lock out during the delegate call.
Don't forget that you can use 'add' and 'remove' (similar to 'get' and
'set' for properties) on the event declaration to add implicit locking if
you want.


Indeed, and this is what I'd suggest, as locking on "this" or the type
is a bad idea. See
http://www.pobox.com/~skeet/csharp/t...ckchoice.shtml

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Apr 26 '06 #6
Jon Skeet [C# MVP] <sk***@pobox.com> wrote:
Barry Kelly <ba***********@gmail.com> wrote:
MORE IMPORTANTLY: Is there any legitimate way to connect a single event
handler instance to multiple event generators running in separate threads?
If so, how is synchronization handled within the event handler object?


It's not thread-safe. The += operator on events which don't have explicit
an add and remove is simply a method call to a method called
add_<yourEventNameHere>, with a body which performs += on the delegate
behind the event.


Not true - a field-like event will lock on *something*, according to
the C# spec. In 1.1, it would always be "this" or
typeof(TheTypeInvolved); in 2.0 it can be a hidden object if the
compiler so desires.

(The MS compiler still just makes the add_XXX method synchronized as
far as I've seen; i.e. it locks on "this" or the type.)


You're right. I checked before I posted with Reflector. I checked again,
and I notice I missed the [MethodImpl(MethodImplOptions.Synchronized)]
attribute.

It's slightly odd that C# leaves out Java's synchronized method semantics
(for good reasons, as you mention, IMHO), yet includes it automatically
for event subscription!

-- Barry
Apr 26 '06 #7

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

Similar topics

1
by: Elbert Lev | last post by:
I started with Python two weeks ago and already saved some time and efforts while writing 2 programs: 1. database extraction and backup tool, which runs once a month and creates a snapshot of...
2
by: pradyumna | last post by:
In Project settins - C/C++ - Code Generation, what is the difference between the option "Multithreaded" and "Multithreaded DLL". I understand that on selecting multithreaded option, single and...
0
by: Nicholas Beenham | last post by:
Hi all, I'm having problems with a udpclient with multicasting and then waiting for a response and if none arrives closes after a few seconds. I have the client multicasting fine but am having...
0
by: gregory_may | last post by:
I posted this in the dotnet.framework group with no responce yet, maybe someone in these groups can point me in the right direction? Or maybe I need to use something already in .Net to get an IGMP...
0
by: POgletree | last post by:
I need to set up a small client/server or, best solution, a peer-to-peer system to swap data strings between wide spread users. I've looked at IP multicasting and it seems like a reasonable...
3
by: groups | last post by:
Hi all, I've recently ported a rather large C application to run multithreaded. A few functions have seriously deteriorated in performance, in particular when accessing a rather large global...
3
by: | last post by:
Is it possible to have just a multithreaded sub procedure? What I need is a timer time_elapsed event (2 sec interval) send params to a sub that is multithreaded. I have a COM component used to...
3
by: Jake K | last post by:
I have a multithreaded application that I now want to convert into a Windows Service. Does application.run work in a windows service? Are there things to take into consideration when creating a...
9
by: Sayudh27 | last post by:
Hi all, I am a relatively new programmer in C++...I need to write a code that performs multicasting as well as returns the data-packets in a decompressed form.Data-receipt seems to work...
1
by: Nick | last post by:
Does any one have a simple wcf of udp multicating other than the one posted here http://wcf.netfx3.com/files/folders/transport_channels/entry5235.aspx I would like a program with just the basics...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
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: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
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
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
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...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

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.