Quantcast
Channel: Visual C# forum
Viewing all articles
Browse latest Browse all 31927

Unsubscribing from a custom event accessor

$
0
0

I have the below sample code. When I unsubscribe from the Onchange event. My anonymous method still handles the event. What is the proper way to unsubscribe from the defined event below?

using System;

using System.Collections.Generic;

using System.Threading.Tasks;

namespace Listing_1_85

{

    classProgram

    {

        static void Main()

        {

            Pub p =newPub();

            p.OnChange += (sender, e) =>

                Console.WriteLine("Event raised: {0}", e.Value);

           // how can I unsubscribe from the OnChange event 

            p.Raise();  

        }

    }

    publicclass MyArgs : EventArgs

    {

        public MyArgs(int value)

        {

            Value = value;

        }

        public int Value { get; set; }

    }

    publicclassPub

    {

        int val = 0;

        private eventEventHandler<MyArgs> onChange =delegate { };

        public eventEventHandler<MyArgs> OnChange

        {

            add

            {

                lock (onChange)

                {

                    onChange +=value;

                    Console.WriteLine("Eventhandler attached\n");

                }

            }

            remove

            {

                lock (onChange)

                {

                    onChange -=value;

                    Console.WriteLine("Eventhandler dettached\n");

                }

            }

        }

        public void Raise()

        {

            val++;

            onChange(this,newMyArgs(val));

        }

    }

}


dblk


Viewing all articles
Browse latest Browse all 31927

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>