I have an event handler in a class which doesnt seem to trigger. I wonder if anyone had any ideas on why this may be happening (or not happening as is the case).
The class inherits from another class and basically listens for messages from a message queue. When a message hits the queue the method onMessage() is called.
From my (winforms, c#, .net 3.5) UI form, I'm trying to get the received message(s) back to the UI.
If I call the method onMessage() manually from the instance on my form, the eventhandler does trigger correctly and passMessage is executed on my UI form.
But when I receive a message thats come automated from the queue I'm listening on, the event handler is not triggered. I dont ever call the onMessage() method, that happens automatically.
Does anyone have any ideas why the event handler is not triggering when onMessage() is called everytime I receive a message?
Thanks
UI:
private void btnConnect(object sender, EventArgs e)
{
MessageQueue myMQ = new MessageQueue();
myMQ.Connect(...);
//Register handler
myMQ.MsgTrigger += new EventHandler(passMessage);
}
public void passMessage(object s, EventArgs e)
{
Console.WriteLine(s.ToString()); //Not sure if this is a good way to pass back a value
}
Class:
namespace MQListener
{
class MessageQueue : MQ.MessageListener
{
public event EventHandler MsgTrigger;
public virtual void onMessage(MQ.Message Message)
{
MQ.TextMessage txtMessage = (MQ.TextMessage)Message;
String MsgBody = txtMessage.getMessage();
Console.WriteLine(MsgBody);
object objMsg = (object)MsgBody;
var _Trigger = MsgTrigger;
if(_Trigger != null)
_Trigger(objMsg, null);
}
}
}
Your event subscription should happen before you connect:
private void btnConnect(object sender, EventArgs e)
{
MessageQueue myMQ = new MessageQueue();
//Register handler
myMQ.MsgTrigger += new EventHandler(passMessage);
myMQ.Connect(...);
}
You can only update controls from the UI thread, so to prevent the error "'txtMessage' accessed from a thread other than the thread it was created on.", you need to check the control's InvokeRequired property. If true, you need to call the Invoke() method. See this SO question: Automating the InvokeRequired code pattern
Related
I have a class with EventHandler bindings at the constructor, that will be instantiated thousand times within application lifecycle. The question is: Will this approach leads to memory/thread leaks?
I did this way (code below), because I need to be notified every time SomeMethod() runs, whatever instance run it. Foo class (the publisher) will be short-lived, however the handlers will live until the application closes.
I ask this because, when working with Windows Forms, each form can hold several event handlers/delegates and everything is fine because all those delegates are inside the form and will be disposed when the form closes. But how about static event handlers/delegates, that could be even on separate projects?
Will I need to write a destructor to detach those event handlers?
Should I go with Weak Event Pattern?
Restriction: I must do this with .NET 3.5. I know I could do this with TPL, setting a "Fire and Forget" Task.
Thank you in advance.
Code:
public class Foo
{
public event EventHandler SomeEvent;
public Foo()
{
SomeEvent += FooHandlers.Foo_SomeEvent1;
SomeEvent += FooHandlers.Foo_SomeEvent2;
}
public void RaiseEvents(EventHandler evt, EventArgs args)
{
var eventObj = evt;
var listeners = eventObj.GetInvocationList();
foreach (var listener in listeners)
{
var method = (EventHandler)listener;
ThreadPool.QueueUserWorkItem(callBack => method(this, args));
// Handlers will do a lot of things, so I don't want
// them blocking the Main thread
}
}
public void SomeMethod()
{
// do something here
RaiseEvents(SomeEvent, new EventArgs());
}
}
public static class FooHandlers
{
public static void Foo_SomeEvent1(object sender, EventArgs e)
{
//do something here
}
public static void Foo_SomeEvent2(object sender, EventArgs e)
{
//do something different here
}
}
Since your handlers are static methods the delegate you're adding to the event doesn't have an object instance, so there is no object instance being kept alive for the duration of the object with the event.
And even if you did use an object instance to attach the handler, it wouldn't be a problem, because the object with the event is short lived. The only time there is a problem is when the object with the event is long lived, and the object that has a handler to itself assigned is short lived, and consumes a lot of resources to keep alive.
I am using the C wrapper of UIAutomation to listen for events.
Specifically, I'm looking for a focus event. When that focus event happens, I'm simply logging to the console, and unbinding the event.
Problem is - the program seems to stall/"die" on the automation.RemoveAllEventHandlers() call. The line below that never gets executed (doesn't print to console, breakpoint doesn't get hit.)
My guess is this is a threading issue - automationis created on a thread, but the event gets called on a different thread, and a big issue ensues. Is this the problem? If so/if not - what is and how do I fix it?
Below is the code:
public class FocusListener
{
private readonly CUIAutomation _automation;
public FocusListener()
{
_automation = new CUIAutomation();
_automation.AddFocusChangedEventHandler(null, new FocusChangeHandler(this));
Console.WriteLine("Added a focus event!");
}
public void On_WindowClicked()
{
Console.WriteLine("Window clicked!");
_automation.RemoveAllEventHandlers(); // program seems to die right here..
Console.WriteLine("Focus event removed"); // this line never gets executed..
}
}
public class FocusChangeHandler : IUIAutomationFocusChangedEventHandler
{
private readonly FocusListener _listener;
public FocusChangeHandler(FocusListener listener)
{
_listener = listener;
}
public void HandleFocusChangedEvent(IUIAutomationElement sender)
{
if (sender.CurrentControlType == UIA_ControlTypeIds.UIA_WindowControlTypeId)
{
_listener.On_WindowClicked();
}
}
}
According to: https://msdn.microsoft.com/en-us/library/windows/desktop/ee671692%28v=vs.85%29.aspx
It is safe to make UI Automation calls in a UI Automation event handler, >because the event handler is always called on a non-UI thread. However, when >subscribing to events that may originate from your client application UI, you >must make the call to IUIAutomation::AddAutomationEventHandler, or a related >method, on a non-UI thread (which should also be an MTA thread). Remove event >handlers on the same thread.
Is there a way to specify an order or priority to handle registered event delegates? For example, I have an event that I would like processed immediately before any other events, but I want other objects to be allowed to register listeners to the event as well. How can this be accomplished?
Lets say I want proc1 to always run before proc 2.
class MessageProcessor
{
private DataClient Client;
public MessageProcesser(DataClient dc)
{
Client = dc;
Client.MessageReceived += ProcessMessage;
}
void proc1(MessageEventArgs e)
{
// Process Message
}
}
class DataClient
{
public event MessageReceievedHandler MessageReceived;
}
void main()
{
DataClient dc = new DataClient();
MessageProcessor syncProcessor = new MessageProcessor(dc); // This one is high priority and needs to process all sync immediately when they arrive before any data messages
MessageProcessor dataProcessor= new MessageProcessor(dc); // This one can process the data as it has time when sync messages are not being processed.
// do other stuff
}
The reason for doing this, I have a server that is sending messages over a UDP stream. It will send sync messages before a burst of data. I realize both handlers will fire when a sync message is received, but to decrease latency I would like the syncProcessor objects events processed before the dataProcessor events. This would decrease the latency of the Sync Message being processed.
In addition, someone else on my team may want to register events to process specific messages also. They may have their own object that will register an event (May not be MessageProcessor), even still the Sync message should have as low latency as possible.
EDIT Made the objective more clear with a better example.
When you subscribe to an event multiple times, there is no possible way to be sure of the execution order of your handlers when the event is fired.
According to this answer, the order in the subscription order, but as the post author said, it's an implementation detail and you must not rely on it.
You could of course write your own "event manager" (see dirty example below) that executes your handlers in a known order, but I don't think it would be a good idea. Maybe you should re-design your event to remove your requirement.
public class MyClass
{
// Could be anything...
public delegate void MyEventHandler(object sender, EventArgs e);
public event MyEventHandler TestEvent;
public void Test()
{
if (this.TestEvent != null)
{
this.TestEvent(this, EventArgs.Empty);
}
}
}
public class EventManager
{
private List<EventHandler> Handlers = new List<EventHandler>();
public void AddHandler(EventHandler handler)
{
this.Handlers.Add(handler);
}
public void RemoveHandler(EventHandler handler)
{
this.Handlers.Remove(handler);
}
public void Handler(object sender, EventArgs e)
{
foreach (var z in this.Handlers)
{
z.Invoke(sender, e);
}
}
}
private static void Main(string[] args)
{
MyClass test = new MyClass();
EventManager eventManager = new EventManager();
// Subscribes to the event
test.TestEvent += eventManager.Handler;
// Adds two handlers in a known order
eventManager.AddHandler(Handler1);
eventManager.AddHandler(Handler2);
test.Test();
Console.ReadKey();
}
private static void Handler1(object sender, EventArgs e)
{
Console.WriteLine("1");
}
private static void Handler2(object sender, EventArgs e)
{
Console.WriteLine("2");
}
In this case, you are better off simply calling the second event at the end of the first event, etc.
If this is your own event that you defined, then your best bet might be to extend it to have a BeforeMessageReceived, MessageReceived and AfterMessageReceived events. (okay, so maybe MessageProcessed would be a better root, since you can know before a message is received).
This will give you more control over exactly where different event handlers occur.
You see the same before, event, after patten all over the place.
Im going to go out on a limb and say no. AFAIK events are dispatched ASYNCHRONOUSLY by nature. So that will be dispatched in the order they are bound. however the results may return in a different order. The only way would be to dispatch your 2nd event inside the callback for the first event. This is not language specific, just more on the architecture of events.
In your example since the calls are void y not run proc2 at the end of proc1?
I've created an event handler that simply returns a list of objects that I receive from a web service when the call completes.
Now I went ahead and ran the app in debug mode and found out that the first time the event is called it works perfectly, but immediately after it completes the event is being fired for a second time. I've checked and am absolutely sure I am not calling the event more than once in the receiver class.
This is my first shot at creating custom event handlers inside my applications so I am not entirely sure the implementation is 100% accurate.
Any ideas of what might be causing this? Is the way I created the event handler accurate?
This is the DataHelper class
public class DataHelper
{
public delegate void DataCalledEventHandler(object sender, List<DataItem> dateItemList);
public event DataCalledEventHandler DataCalled;
public DataHelper()
{
}
public void CallData()
{
List<DataItem> dataItems = new List<DataItem>();
//SOME CODE THAT RETURNS DATA
DataCalled(this, dataItems);
}
}
This is where I subscribed to my event:
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
GetNewDataItems();
}
private void GetNewDataItems()
{
try
{
DataHelper dataHelper = new DataHelper();
dataHelper.CallData();
dataHelper.DataCalled += new DataHelper.DataCalledEventHandler(dataHelper_DataCalled);
}
catch
{
//Handle any errors
}
}
}
void dataHelper_DataCalled(object sender, List<DataItem> dataItemsList)
{
//Do something with results
//NOTE: THIS IS WHERE THE EXCEPTION OCCURS WHEN EVENT IS FIRED FOR SECOND TIME
}
Probably you added the delegate twice, is it possible?
In this case the problem is not in who calls the delegate but in who adds the delegate to the event.
Probably you did something like...
private Class1 instance1;
void callback(...)
{
}
void myfunction()
{
this.instance1.DataCalled += this.callback;
this.instance1.DataCalled += this.callback;
}
If not, try to add a breakpoint where you subscribe to the event and see if it is called twice.
As a side note, you should always check for null when calling an event, if there is no subscriber you can get a NullReferenceException.
I would also suggest you to use a variable to store the event delegate to avoid the risk of multithreading failure.
public void CallData()
{
List<DataItem> dataItems = new List<DataItem>();
var handler = this.DataCalled;
if (handler != null)
handler(this, dataItems);
}
Edit: since now I see the code, is obvious that each time you call the GetNewDataItems method you are subsribing every time to the event.
Do in such a way you subscribe only once, for example, in constructor, or store your variable somewhere or deregister the event when you finish.
This code contains also a probable memory leak: every time you add a delegate you keep alive both the instance that contains the event and the instance that contains the subscribed method, at least, until both are unreferenced.
You can try to do something like this...
void dataHelper_DataCalled(object sender, List<DataItem> dataItemsList)
{
// Deregister the event...
(sender as Class1).DataCalled -= dataHelper_DataCalled;
//Do something with results
}
In this way however you must ensure that if there is not an exception during the event registration the event will be fired or you have again memory leaks.
Instead of an event perhaps you need just a delegate. Of course you should set your delegate field to null when you want to release the delegate.
// in data helper class
private DataHelper.DataCalledEventHandler myFunctor;
public void CallData(DataHelper.DataCalledEventHandler functor)
{
this.myFunctor = functor;
//SOME CODE THAT RETURNS DATA
}
// when the call completes, asynchronously...
private void WhenTheCallCompletes()
{
var functor = this.myFunctor;
if (functor != null)
{
this.myFunctor = null;
List<DataItem> dataItems = new List<DataItem>();
functor(this, dataItems);
}
}
// in your function
... dataHelper.CallData(this.dataHelper_DataCalled); ...
The below lines on your code should be flipped. That is
These lines
dataHelper.CallData();
dataHelper.DataCalled += new DataHelper.DataCalledEventHandler(dataHelper_DataCalled);
Should be:
dataHelper.DataCalled += new DataHelper.DataCalledEventHandler(dataHelper_DataCalled);
dataHelper.CallData();
Because you first need to attach the event handler and then call other methods on the object which can raise the event
I have a C# 2.0 application with a form that uses a class that contains a thread.
In the thread function, rather than call the event handler directly, it is invoked. The effect is that the owning form does not need to call InvokeRequired/BeginInvoke to update its controls.
public class Foo
{
private Control owner_;
Thread thread_;
public event EventHandler<EventArgs> FooEvent;
public Foo(Control owner)
{
owner_ = owner;
thread_ = new Thread(FooThread);
thread_.Start();
}
private void FooThread()
{
Thread.Sleep(1000);
for (;;)
{
// Invoke performed in the thread
owner_.Invoke((EventHandler<EventArgs>)InternalFooEvent,
new object[] { this, new EventArgs() });
Thread.Sleep(10);
}
}
private void InternalFooEvent(object sender, EventArgs e)
{
EventHandler<EventArgs> evt = FooEvent;
if (evt != null)
evt(sender, e);
}
}
public partial class Form1 : Form
{
private Foo foo_;
public Form1()
{
InitializeComponent();
foo_ = new Foo(this);
foo_.FooEvent += OnFooEvent;
}
private void OnFooEvent(object sender, EventArgs e)
{
// does not need to call InvokeRequired/BeginInvoke()
label_.Text = "hello";
}
}
This is obviously contrary to the method used by Microsoft APIs that use background threads like System.Timers.Timer and System.Io.Ports.SerialPort. Is there anything inherently wrong with this method? Is it dangerous in some way?
Thanks,
PaulH
Edit: also, what if the form did not subscribe to the event right away? Would it clog the Form's message queue with events the form wasn't interested in?
This is a threadsafe call, the method will be processed in the thread of the form.
Nothing wrong with it when looking at it from a conceptual perspective.
Timers are more elegant for such tasks, though. However, it could be that a timer with an interval of 10ms slows down the GUI, that's probably why Invoke was used.
You do not need a call to InvokeRequired, since it is clear that the Control is in an other thread. Also, BeginInvoke only needs to be called when you want to call a method asynchronously, which obviously isn't the case here.
Regarding your edit:
No, the message queue will not be clogged. No event will be fired if no handler has been registered. Take another look at your code ;)