简体   繁体   中英

C#,WPF Subscribing for an external event in code-behind

I'm trying to subscribe for an event in an external class using code-behind in WPF and I obviously fail.

I have an external library which uses ActiveMQ.NMS API to communicate with a broker and asynchronously listen on a topic. To do the second we need to register to an event called consumer.Listener . Everything worked perfect until creating a WPF project referencing the library and trying to subscribe to the event from code-behind (in code behind I called instance of an object responsible for communicating with the broker, created the handler and registered it).

As I understand now the reason behind my problem is Thread Affinity, however I would still love to know how to do what I was trying to do from code-behind even though most developers will immediately despise me for even thinking about such a thing. As a side note: it's a bit funny that debugger without giving any reason just skips some lines in methods if it feels like doing that.

Also, what is the recommended pattern for dealing with external events in WPF?

Thank you for your feedback:)

I'm going to assume that when you say "external events" you simply mean public events, exposed by an object of some kind. However you use the term external when referring to the library which uses ActiveMQ.NMS API... so I assume in that context you mean that it's a library outside of your code base, something you import, reference etc. Please correct / edit your post if I'm misunderstanding.

Assuming "consumer" is an object inside the library you reference with your project, once you instantiate "consumer", you should have a piece of code that looks something like:

consumer.Listener += new WhateverTheHandlerEventArgsIsCalledHere(consumer_Listener);

After you finish typing in "new" the intellisense should fill out the rest for you automatically if you hit the tab key twice.

I don't know why you think most developers would despise you for thinking about that... it's usually a good practice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM