473,789 Members | 3,123 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Firing cross thread events...

All,

I have a worker thread that fires events across threads to both GUI objects
and thread agnostic objects. My code is working but I want to be assured
that it did it "the right way"... Question: Is there a better way?

According to the .NET docs that I read all that I have to do to fire my
custom "OnSynchronizat ionStatusChange ()" event is:

protected void OnSynchronizati onStatusChange( Synchronization EventArgs e)
{
if (Synchronizatio nStatusChange != null)
{
Synchronization StatusChange(th is, e);
}
}

This did NOT work across threads - GUI objects received notification on the
worker thread not the GUI thread. Soooo, I reworked it as follows - this
works but I feel that I missed something because I don't feel that I should
have to do this:

protected void OnSynchronizati onStatusChange( Synchronization EventArgs e)
{
if (Synchronizatio nStatusChange != null)
{
object[] args = new object[2];
args[0] = this;
args[1] = e;

foreach (System.Delegat e d in
Synchronization StatusChange.Ge tInvocationList ())
{
ISynchronizeInv oke isi = d.Target as ISynchronizeInv oke;
if (isi == null)
{
d.DynamicInvoke (args);
}
else
{
isi.BeginInvoke (d, args);
}
}
}
}

Is there a better way to do this??
Nov 17 '05 #1
5 10806
Richard,

That's an interesting requirment. Because of that requirement I'm
assuming other threads are adding and removing event handlers to the
Synchronization StatusChange event. If that's the case then the
OnSynchronizati onStatusChange method might have a problem after
checking to see if Synchronization StatusChange is null. You might get
a NullReferenceEx ception on the call to
Synchronization StatusChange.Ge tInvocationList (). Fortunately,
delegates are immutable so grabbing a local reference to
Synchronization StatusChange before making the check will solve that
problem. There might be other problems. I'll try to take a closer
look later. Right now I'm going home!

Brian

Richard wrote:
All,

I have a worker thread that fires events across threads to both GUI objects
and thread agnostic objects. My code is working but I want to be assured
that it did it "the right way"... Question: Is there a better way?

According to the .NET docs that I read all that I have to do to fire my
custom "OnSynchronizat ionStatusChange ()" event is:

protected void OnSynchronizati onStatusChange( Synchronization EventArgs e)
{
if (Synchronizatio nStatusChange != null)
{
Synchronization StatusChange(th is, e);
}
}

This did NOT work across threads - GUI objects received notification on the
worker thread not the GUI thread. Soooo, I reworked it as follows - this
works but I feel that I missed something because I don't feel that I should
have to do this:

protected void OnSynchronizati onStatusChange( Synchronization EventArgs e)
{
if (Synchronizatio nStatusChange != null)
{
object[] args = new object[2];
args[0] = this;
args[1] = e;

foreach (System.Delegat e d in
Synchronization StatusChange.Ge tInvocationList ())
{
ISynchronizeInv oke isi = d.Target as ISynchronizeInv oke;
if (isi == null)
{
d.DynamicInvoke (args);
}
else
{
isi.BeginInvoke (d, args);
}
}
}
}

Is there a better way to do this??


Nov 17 '05 #2

I don't think that anybody is expressly -= unsubscibing from my event; which
raises a question --> if they DON'T unsubscribe does not my event's
invocation list hold a strong reference to their object such that their
object will not get collected until my object is collected?

Actually in my case I will get away with it because people use my code to
connect/disconnect a wireless modem card; aka they always have scope/span >=
to me...
OnSynchronizati onStatusChange method might have a problem after
checking to see if Synchronization StatusChange is null. You might get
a NullReferenceEx ception on the call to
Synchronization StatusChange.Ge tInvocationList (). Fortunately,
delegates are immutable so grabbing a local reference to
Synchronization StatusChange before making the check will solve that
problem.


Good point, I will add local reference...

But in general am I doing this correctly? It seems to me that the event
plumbing should have enough smarts to know that it needs to use Invoke() -->
am I missing something here?

As Robert W. points out to me in his threading post - couldn't I maybe just
set the Form's "ISynchronizeIn voke.RequiresIn voke" property to true -
would'nt that then allow me to use the original form of invoking the event as
documented in .NET guides rather than creating the argument array and
manually looping? -- Hmmm, I will try this tomorrow...


Nov 17 '05 #3
Richard wrote:
I don't think that anybody is expressly -= unsubscibing from my event;
If you're sure no one is unsubscribing from the event then you
shouldn't have a problem.
which
raises a question --> if they DON'T unsubscribe does not my event's
invocation list hold a strong reference to their object such that their
object will not get collected until my object is collected?
Garbage collection isn't the issue here. I can better explain the
problem with actual code.

private void SomeMethod()
{
// At this point SomeEvent has at least one reference to a delegate.
if (SomeEvent != null)
{
// The test is true, but immediately after it another thread
// removes the last event handler.

// SomeEvent is now null again so this line will throw an
// exception.
SomeEvent();
}
}

To fix that problem you would do the following.

private void SomeMethod()
{
// This works because delegates are immutable.
SomeEventHandle r copy = SomeEvent;
if (copy != null)
{
copy();
}
}
Actually in my case I will get away with it because people use my code to
connect/disconnect a wireless modem card; aka they always have scope/span>=
to me...
OnSynchronizati onStatusChange method might have a problem after
checking to see if Synchronization StatusChange is null. You might get
a NullReferenceEx ception on the call to
Synchronization StatusChange.Ge tInvocationList (). Fortunately,
delegates are immutable so grabbing a local reference to
Synchronization StatusChange before making the check will solve that
problem.
Good point, I will add local reference...

But in general am I doing this correctly?


Yes, actually I believe it is. To clean it up a bit here's what I
would do:

protected void OnSynchronizati onStatusChange( *
Synchronization EventArgs e)
{
YourEventHandle r copy = Synchronization StatusChange;

if (copy != null)
{
object[] args = new object[] { this, e };

foreach (Delegate d in copy.Ge*tInvoca tionList())
{
ISynchronizeInv oke isi = d.Target as ISynchronizeInv oke;
if (isi != null && isi.InvokeRequi red)
{
isi.BeginInvoke (d, args);
}
else
{
d.DynamicInvoke (args);
}
}
}
}
It seems to me that the event
plumbing should have enough smarts to know that it needs to use Invoke() -->
am I missing something here?
It does not.
As Robert W. points out to me in his threading post - couldn't I maybe just
set the Form's "ISynchronizeIn voke.RequiresIn voke" property to true -
would'nt that then allow me to use the original form of invoking the event as
documented in .NET guides rather than creating the argument array and
manually looping? -- Hmmm, I will try this tomorrow...


No, the InvokeRequired property is readonly.

Nov 17 '05 #4

Brian Gideon wrote:
Richard,

There might be other problems. I'll try to take a closer
look later.

Brian


I should also add that there will be race condition when other threads
are subscribing and unsubscribing to the event. For example, consider
the following code.

private void Thread_A()
{
sharedClass.You rEvent += new EventHandler(th is.YourHandler) ;
}

private void Thread_B()
{
sharedClass.You rEvent += new EventHandler(th is.YourHandler) ;
}

When running simultaneously you might have the following sequence.

Thread A: Reads delegate reference from event
Thread B: Reads delegate reference from event
Thread A: Adds event handler to local delegate reference
Thread B: Adds event handler to local delegate reference
Thread A: Writes delegate reference to event
Thread B: Writes delegate reference to event

As you can see thread B will wipe out the changes thread A made. You
will need to make the += and -= operators thread-safe.

Nov 17 '05 #5
Brian Gideon <br*********@ya hoo.com> wrote:

<snip>
As you can see thread B will wipe out the changes thread A made. You
will need to make the += and -= operators thread-safe.


For sample code on this front, see
http://www.pobox.com/~skeet/csharp/t...ckchoice.shtml

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #6

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

Similar topics

4
3579
by: Bob | last post by:
Hi, Moving a project from .net 2003 -> 2005 Beta 2 Windows App. Main Window is start object. Main window spawns a thread. After doing some work this thread raises an interrupt. The event carries a reference to the class that raised it plus an instantiated, empty eventarg. RaiseEvent LineStateChange(Me, e) The 'RaiseEvent' errors in 2005 with Cross thread...
8
4856
by: Pieter | last post by:
Hi, I'm having some weird problem using the BackGroundWorker in an Outlook (2003) Add-In, with VB.NET 2005: I'm using the BackGroundWorker to get the info of some mailitems, and after each item I want to raise the ProgressChanged-event to update the DataGridView. It works fine when only one Progresschanged is fired, but at the second, third, fopurth etc it raises everytile a 'Cross-thread operation not valid"-exception on lmy...
11
8689
by: HairlipDog58 | last post by:
Hello, There are several 'cross-thread operation not valid' exception postings in the MSDN discussion groups, but none address my exact situation. I have authored a .NET component in Visual C# .NET 2003 that is capable of firing several types of events to notify user of errors, data changes, etc. The component uses a thread to perform background communications and if there is an error or data-change fires an event to notify the user....
18
6605
by: Dave Booker | last post by:
I have a Thread making a callback to a Form function that alters Form data. Of course, the debugger is telling me, "Cross-thread operation not valid: Control 'FormTest' accessed from a thread other than the thread it was created on." But I am locking before I touch the shared data, so do I actually need to worry about this, or is it just the debugger being oversimplistic? Specifically, I have:
10
6890
by: Daniel | last post by:
Hi guys I have a form with my gui on, just some list boxes. And a class that handles incoming data. i want to, on receiving data, update my gui. However even though i have an instance created in my class handling the receiving data of the gui form if i try and update the gui directly i get a
4
5319
by: Paul Cheetham | last post by:
Hi, I have a couple of classes that I am using to read a swipe-card reader attached to the serial port (c# VS 2005 Pro). I have a SerialComm class which actaully reads the serial port, and a CardReader class which validates the number etc. Neither of these classes inherit from any other classes / controls. The SerialComm class is instantiated by the Cardreader class, so in the
5
3603
by: nospam | last post by:
Hi all. I have encountered a "Cross-thread operation not valid" error in a test program I created and although I have came up with a solution I don't like the performance of the program. I hope perhaps some experts here can help me out. Here is what my program consists of: 1) A form containng several tabs, one of which contains a ListView
0
1108
by: Peter Duniho | last post by:
On Mon, 02 Jun 2008 17:14:31 -0700, NvrBst <nvrbst@gmail.comwrote: The general rule is that if it's not one of the five members listed in the docs (under Control.Invoke and other pages), you must use Control.Invoke() or Control.BeginInvoke() to access _any_ member of a Control instance. Now, as you've found, some members not in that list can be successfully used without the cross-thread exception being thrown. One that I am...
3
3743
by: kimiraikkonen | last post by:
Hi, I was looking for an example on CodeProject and saw an interesting thing, i downloaded the article source code and converted to my VB 2005 Express and compiled with no problem, however when i debug the program to and split a file(size doesn't matter) in debug mode with VS, that is, a file merge-split tool, nearly i always get a "cross- thread operation not valid" error for progress bar, whereas double clicking and launching program...
0
9511
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
10408
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
10199
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...
1
10139
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9983
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...
1
7529
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6768
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
5417
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...
1
4092
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.