Is the event fired, when previous handler didn't finish? - c#

Does SqlDependency (for example) fires the OnChange event, when the invocation of previous event handler didn't finish? (Assume that OnDependencyChange method is very time consuming)
What exactly happens?
SqlDependency dependency=new SqlDependency(command);
// Subscribe to the SqlDependency event.
dependency.OnChange += new
OnChangeEventHandler(OnDependencyChange);

I am not that familiar with the SqlDependency class, but per the MSDN documenation:
The OnChange event may be generated on
a different thread from the thread
that initiated command execution.
That seems to open up the possibility that two event handlers can run simultaneously. There is no documentation that states that all event handlers invoked from raising the event must complete before the event can be raised again. The safe thing to do is to assume multiple simultaneous invocations of the event can occur. Because the event is raised on an undefined thread you will have to guard against the problems of concurrency anyway.

In normal single threaded program not it will not. Try following:
Add windows forms app. Add a button to a form. Use following method to handle button's click event:
private void Buttonclick(object sender, EventArgs e)
{
Thread.Sleep(25);//SUSPEND CURRENT THREAD
}
you will not be able to click the button until the call to Thread.Sleep(25) finishes its work (suspend thread for 25 secs). You can test this in Console app also.

Related

When exactly are events executed in C#?

I have developed a C# application which makes heavy use of events. Now this application is occasionally doing funny things that I cannot understand or track down to a specific cause why they should occur. I reckon that the cause for these intermittent malfunctions is some sort of concurrency or race condition which I did not anticipate.
How exactly are events handled in C#? If an event is raised, will (a) the portion of code attached to that event be executed immediately? Or will the event (b) be put on a stack of events and be executed whenever .NET deems it suitable for execution while other code is executed in the meantime?
If an event is raised, will the portion of code attached to that event be executed immediately?
Well, yes and no. Events are multicast delegates, so there might be zero, one or many "portions of code" attached to an event. In the scenario where there are many, clearly one of them has to go first and one of them has to go second. The one that goes second isn't executed immediately upon the event being raised; it's executed immediately upon the first event handler completing normally.
will the event be put on a stack of events and be executed whenever .NET deems it suitable for execution while other code is executed in the meantime?
Suppose your application is badly written and hangs the UI. While the UI is hung, the user clicks on button 1 and button 2. Since the application is hung, nothing visible happens. The events for button 1 and button 2 being clicked do not fire. But Windows has created a message queue and enqueued on it the fact that button 1 and button 2 have pending clicks that need to be processed when the application unhangs itself. When the message loop is pumped then the button 1 click event fires. When it is done doing its thing, the message loop is pumped again and the button 2 click event fires.
So yes, in that sense events are queued up and executed later, but it is not "when .NET deems it suitable"; it's when the thread that is processing the message queue starts processing the message queue again. There's no mysterious Windows policy in here controlling your code.
It entirely depends on the event raising (and subscription) code.
If you're raising the event like this:
EventHandler handler = MyEvent;
if (handler != null)
{
handler(this, EventArgs.Empty);
}
or something similar, then all the event handlers will be executed immediately. That's the typical implementation... you have to work a bit harder to put each event delegate into WinForms message queue or something like that.
If you could give us more information about what events you're talking about and how they're implemented, we may be able to help you more.
For more information on events and delegates (and the difference between them) you may wish to read my article on the topic.
C# events, just like the rest of delegates, are executed immediately when triggered.
Unless explicitly implemented otherwise, events are called synchronously.
Typically the code that triggers an event looks like that:
public event EventHandler MyEvent;
protected virtual void OnMyEvent()
{
EventHandler handler = MyEvent; // keep a copy to avoid race conditions
if (handler != null)
handler(this, EventArgs.Empty);
}
As you can see from this code, event handlers are called immediately and synchronously from the OnMyEvent method.
I believe your question has been answered here:
Are Event Handlers processed Asynchronously?
In short, it depends on your implementation, but the default event handling is processed synchronously. There are, however, ways to make it asynchronous.
As stated in the previous awnser, it entirely depends on the code that is raising the event or handeling the event.
What above examples are missing is properly code on how to raise/handle events. I'm aware that they're just quick examples, but nonetheless, good practise is important.
If you want good examples/material on how events can be properly processed in C#, you could take a look at this article: http://www.codeproject.com/KB/cs/event_fundamentals.aspx

Do firing events in C# block the current thread execution?

If I'm firing the event:
var handler = OnMyEvent;
if (handler != null)
{
handler(some_info);
}
then will the execution thread wait until all suscriber methods return to continue the execution after line:
handler(some_info);
?
Or events are fired "in another thread", meaning that it automatically goes to the next line after handler(some_info)?
Events are fired on the same thread and it will block until they are completed. Of course the event handling code itself can spawn another thread and return immediately but this is completely different matter.
Also note that events like button clicks in a desktop applications like Windows Forms apps are put on a message queue and will fire one at a time. i.e. if you press a button and then press another button the second button event will not fire until the first is completed. Also the form will not repaint and will be "not responding" because painting the form is also an event.
Events are fired in the thread that raised them.

What is this line of code?

Often in code I see a line of code, I have an idea it do something about event but not clearly know what it does.
Is it possible that I can attach form A's load event in Form B with this, or what is its benefit?
this.CGForm .Load +=new EventHandler(CGForm_Load);
Yes, it clearly has to do with events.
.Load in this case the the Form.Load event. The += operator adds one event handler to the event. An event can have many event handlers at the same time. Event handlers are just regular method that can be anywhere in your code base. When the event fires all subscribed methods will be called, one after the other.
I see no particular good reason to have FormA listen to the Load event of FormB, but other events might be more interesting, like the Form.Closed event. This is a way to have FormA react to changes in FormB.
Edit
Note that this causes FormA to hold a reference to FormB and FormB won't be garbage collected until FormA releases the reference to FormB (with
this.CGForm .Load -=new EventHandler(CGForm_Load);, note the -=) this is a common cause for memory leaks in .NET.
Subscribing to events from other forms is a "code smell" that can be a potential structure problem with your code. In some cases it is required, but if you have it all over the place your code will be hard to understand and maintain.
What this line means is that you subscribe the method CGForm_Load() to the this.CGForm.Load event. The method CGForm_Load() is the event handler or the callback.
After you run this line, every time the event is raised (in this case - every time the form is loaded), CGForm_Load() will be called automatically.
In order to unsubscribe a callback, use -= like this:
this.CGForm.Load -= new EventHandler(CGForm_Load)
Once an event callback is unsubscribed, the next time the event is raised (if the form is loaded again) the callback will no longer be called.
I find the following metaphor helpful: An event is like a power outlet, and callbacks are like power plugs. Subscribing is like connecting the plug to the outlet, and unsubscribing is like pulling it out. While there is a connection, all invocations of the event trigger the callback.
It simply adds the GCForm_Load method to the Load event on the CGForm. Under the hood when the CGForm is loaded code like the following will execute. Whenever this happens all event subscribers (in this case the method being subscribed here as CGForm_Load) will be invoked.
<pseudocode>
class CGForm
{
public EventHandler<FormLoadedEventArgs> Load;
private void SomeMethodThatLoadsTheForm()
{
LoadForm();
var loadHandlers = Load;
if (loadHandlers != null)
{
loadHandlers(new FormLoadedEventArgs(...));
}
}
}
</pseudocode>
this.CGForm .Load +=new EventHandler(CGForm_Load); subscribes the event handler delegate CGForm_Load to the Load event of the CGForm object.
Documentation about subscribing to events can be found at http://msdn.microsoft.com/en-us/library/ms366768(v=vs.80).aspx .
And index of information about how events work in .NET can be found at http://msdn.microsoft.com/en-US/library/awbftdfh(v=VS.80).aspx

Multiple Threads subscribing same event

What will happen when 10 threads will subscribe to the same event and the event fires?
Which thread will pick it up?
Thread's don't subscribe to events, objects do. When an event fires, all of the registered handlers execute on the same thread (the one that raised the event). There's no built-in facility for events to fire on multiple threads.
A handler can choose to forward the event information to a separate thread, if desired, but that's not part of the built-in mechanism of event dispatch.
If by "event" you mean a Win32 synchronization Event (which is how I read the question) then it depends on how the EventWaitHandle is created. If its manual reset, the event will signal all threads and all will execute. If its auto reset, a single thread will be signalled and executed. Any of your 10 threads waiting on the event could be chosen.
I think what you mean here is that multiple objects on separate threads subscribe to an event.
All of the handlers will be called but on the same thread that invoked the event.
The answer to your question I guess is it depends on the implementation of the event dispatcher... Usually you use a list to keep track of all the event handlers which subscribed to a particular event, so most likely in terms of this kind of implementation, the first handler that gets fired is the first event handler that got subscribed if you of course call all the relevant procedures synchronously, if not, then it depends... just a thought..
If you want to know which object will pick up the event, every object that subscribes to an event will pick up that event, but each will run on the thread that the event occurred on.
If you want to know which object will pick up that event first see ultrajohns answer.
I think if I understand your question. You mean to ask your object exposes a event that user of your object can subscribe. If 10 different users of your object has subscribed to this event, and at some point you fire the event, what would be order (or simultaneously) the event handlers would be invoked?
Answer: Since the event handler execution happens on the same thread who fires it (in this case your object's processing thread) can only process one handler function at a time. The order is not guaranteed (meaning not necessarily first subscriber would executed first and last would be executed last). I hope this answers your question. The bottom line is all 10 handler would be called and none would be in parallel. They will be executed one after another. I have seen people accidentally subscript to save event twice and then seeing the action happening twice and having hard time figuring out why some things are happening multiple times.

C#, Event Handlers and Threading

I'm writing a little chat app, and I have this event handler:
void o_Typing(object sender, EventArgs e)
{
MessageBox.Show("Fired!");
this.Text = "Fired!";
}
o_Typing is a method in a class derived from TabPage. Basically, I want each conversation to have it's own tab.
The event handlers are fired by my Chat object, which is running in another thread. I have 1 thread for UI, and another thread for each Chat conversation (to keep polling the server for new data)
When the event is fired, the MessageBox pops up, but the Tab caption doesn't change. After the event has fired once, it never fires again, leading me to believe that the event is being called in the worker thread, although it is defined in the UI thread.
How can I get my events to be called from the worker thread, and use Invoke() to get them to execute on the UI thread?
There are two options:
1) Make the event handlers thread-safe: use Control.Invoke/BeginInvoke in any event handler which needs to talk to the UI thread.
2) Make the worker thread marshal back to the UI thread before raising the event - in other words, use Control.Invoke as part of the process of raising the event, so that the event handlers will all be called in the UI thread. Depending on how your app is structured, you may not want your event-raising component to know about the UI explicitly - but when it's being constructed you can pass in an ISynchronizeInvoke (which Control implements) and your component can use that to raise its events on the right thread. Of course, that only works (simply, anyway) if every event handler is happy to run on the same thread - but that will often be the case. You'd write something like:
protected void OnFoo(EventArgs args)
{
if (sync != null && sync.InvokeRequired)
{
sync.Invoke((Action) delegate { OnFoo(args) }, null);
return;
}
EventHandler handler = Foo; // Where Foo is the event name
if (handler != null)
{
handler (this, args);
}
}
If you fire your event in code which is executed by your worker thread, then all methods subscribed to the event will be executed under that worker thread.
For GUI-elements you need to look at the Invoke-methods.
Best Regards

Categories

Resources