{"id":419,"date":"2015-02-05T23:37:04","date_gmt":"2015-02-05T15:37:04","guid":{"rendered":"https:\/\/www.techcoil.com\/blog\/?p=419"},"modified":"2018-09-04T22:45:16","modified_gmt":"2018-09-04T14:45:16","slug":"how-to-raise-and-consume-custom-events-in-c","status":"publish","type":"post","link":"https:\/\/www.techcoil.com\/blog\/how-to-raise-and-consume-custom-events-in-c\/","title":{"rendered":"How to raise and consume custom events in C#"},"content":{"rendered":"<p>When something happens asynchronously, the events mechanisms in C# is a good way for different components of our C# programs to notify one another about it. <\/p>\n<p>For example, when the report generation component had the finance report ready, it can raise an event to components that had registered interest in that finance report. <\/p>\n<p>This post documents how we can raise and consume custom events in C#.<\/p>\n<h2>Defining a delegate for components that are interested in the event<\/h2>\n<p>We first define the delegate that will hold C# methods from components which need to be notified when our report is completed by the report generation module. <\/p>\n<p>Components which are interested in the report generation module shall provide a method that returns nothing and accepts a <code>string<\/code> as its only input parameter.<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\npublic delegate void ReportCompletedHandler(string report);\r\n<\/pre>\n<p>I tend to put the definition of the delegate in the same source file that defines the component which will fire the event.<\/p>\n<h2>Defining the event object<\/h2>\n<p>We then define the event object as an instance variable in the class definition of the component which will fire the event.<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\npublic event ReportCompletedHandler reportCompleted;\r\n<\/pre>\n<p>The event keyword defines the delegate that we had defined earlier as a custom event and makes the event available through the variable <code>reportCompleted<\/code>. <\/p>\n<h2>Registering interest in the event<\/h2>\n<p>To register interest in the event, we first define a method which had the same signature as the delegate, <code>ReportCompletedHandler<\/code>.<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nprivate void displayReport(string report) \r\n{\r\n    Console.WriteLine(&quot;Received report: &quot; + report);\r\n}\r\n<\/pre>\n<p>And then add the method as a delegate to the event:<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nreportCompleted += new ReportCompletedHandler(this.displayReport);\r\n<\/pre>\n<h2>Firing the event<\/h2>\n<p>When the report is ready, the report generation component will first check whether there are delegates registered to the <code>reportCompleted<\/code> event. If there are interested parties registered to the event, it will fire the event.<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\n\r\nString report = &quot;&lt;A sample report&gt;&quot;;\r\n\r\nif (reportCompleted != null) \r\n{\r\n    reportCompleted(report);\r\n}\r\n<\/pre>\n<h2>A complete example for this post<\/h2>\n<h3>The delegate and event generator source<\/h3>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\n\/\/ Define delegate for components that are interested in report completion\r\npublic delegate void ReportCompletedHandler(string report);\r\n\r\n\/\/ The event generator source\r\npublic class ReportGenerator\r\n{\r\n    public event ReportCompletedHandler reportCompleted;\r\n\r\n    public void generateReport()\r\n    {\r\n        \/\/ Fire report completed event with report\r\n        string report = &quot;&lt;A sample report&gt;&quot;;\r\n\r\n        if (reportCompleted != null)\r\n        {\r\n            reportCompleted(report);\r\n        }\r\n    }\r\n}\r\n<\/pre>\n<h3>A component that is interested in report completion<\/h3>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\npublic class ReportDisplayer \r\n{\r\n\r\n    public ReportDisplayer()\r\n    {\r\n        \/\/ Register interest in the completed report\r\n        ReportGenerator.getInstance().reportCompleted += new ReportCompletedHandler(this.displayReport);\r\n    }\r\n\r\n    public void displayReport(string report)\r\n    {\r\n        Console.WriteLine(&quot;Diplaying report:&quot;);\r\n        Console.WriteLine(report);\r\n    }\r\n\r\n}\r\n<\/pre>\n<h3>Class that contains the main method to start the program<\/h3>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nusing System;\r\npublic class Program\r\n{\r\n    public static void Main(string&#x5B;] args)\r\n    {\r\n\r\n        \/\/ Set up report displayer\r\n        ReportDisplayer reportDisplayer = new ReportDisplayer();\r\n\r\n        \/\/ Trigger report generation\r\n        ReportGenerator.getInstance().generateReport();\r\n\r\n    }\r\n}\r\n<\/pre>\n\n      <ul id=\"social-sharing-buttons-list\">\n        <li class=\"facebook\">\n          <a href=\"https:\/\/www.facebook.com\/sharer\/sharer.php?u=https%3A%2F%2Fwp.me%2Fp245TQ-6L\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n            <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Facebook.png\" alt=\"Facebook icon\"> Share\n          <\/a>\n        <\/li>\n        <li class=\"twitter\">\n          <a href=\"https:\/\/twitter.com\/intent\/tweet?text=&url=https%3A%2F%2Fwp.me%2Fp245TQ-6L&via=Techcoil_com\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Twitter.png\" alt=\"Twitter icon\"> Tweet\n          <\/a>\n        <\/li>\n        <li class=\"linkedin\">\n          <a href=\"https:\/\/www.linkedin.com\/shareArticle?mini=1&title=&url=https%3A%2F%2Fwp.me%2Fp245TQ-6L&source=https:\/\/www.techcoil.com\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/linkedin.png\" alt=\"Linkedin icon\"> Share\n          <\/a>\n        <\/li>\n        <li class=\"pinterest\">\n          <a href=\"https:\/\/pinterest.com\/pin\/create\/button\/?url=https%3A%2F%2Fwww.techcoil.com%2Fblog%2Fwp-json%2Fwp%2Fv2%2Fposts%2F419&description=\" class=\"pin-it-button\" target=\"_blank\" role=\"button\" rel=\"nofollow\" count-layout=\"horizontal\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Pinterest.png\" alt=\"Pinterest icon\"> Save\n          <\/a>\n        <\/li>\n      <\/ul>\n    ","protected":false},"excerpt":{"rendered":"<p>When something happens asynchronously, the events mechanisms in C# is a good way for different components of our C# programs to notify one another about it. <\/p>\n<p>For example, when the report generation component had the finance report ready, it can raise an event to components that had registered interest in that finance report. <\/p>\n<p>This post documents how we can raise and consume custom events in C#.<\/p>\n","protected":false},"author":1,"featured_media":1189,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"advanced_seo_description":"","jetpack_seo_html_title":"","jetpack_seo_noindex":false,"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":true,"_jetpack_newsletter_tier_id":0,"footnotes":""},"categories":[375],"tags":[20,211,210,209],"jetpack_featured_media_url":"https:\/\/www.techcoil.com\/blog\/wp-content\/uploads\/C-Sharp-Logo.gif","jetpack_shortlink":"https:\/\/wp.me\/p245TQ-6L","jetpack-related-posts":[],"jetpack_likes_enabled":true,"jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts\/419"}],"collection":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/comments?post=419"}],"version-history":[{"count":0,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts\/419\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/media\/1189"}],"wp:attachment":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/media?parent=419"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/categories?post=419"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/tags?post=419"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}