Search code examples
functioneventsc#-4.0delegatescustom-events

How to create a custom events in C#


I'm trying to develop an application using C# wiforms. I want to execute void sendEmail(){} function in a class only when internet connection is up. The method that I used is bool checkConnection(){} function infinitely loops a while loop and sending ping requests to google.com. if the ping is successful, sendEmail(){} function is called by the checkConnection() function.

But i know this is not the best practice of doing this. I'm very confusing about custom events in C#. how to use custom events to accomplish this task. expecting an answer with simple explanation.

Thanks in advance


Solution

  • I understand that you are trying to build a scheduler task like functionality in c#. Based on my understanding, a windows service would do the task for you like listening for the availability of internet and then performing the mail sending operation when the application goes online.

    W.R.To Events, you can build your own event engine that the one that raises the application events when the app runs and then there will be database entries that lists the pending tasks. There will be a background job like a windows service that reads the database and based on the availability of internet or on some condition executes the job.

    If you can be more clear on the exact use-case and what you have tried so far the community can help you better.

    Sample class Observable { public event ImageUploadeventHandler InternetcOnnected;

    public void DoSomething()
    {
        ImageUploadeventHandler handler = InternetcOnnected;
        if (handler != null)
        {
            handler(this, EventArgs.Empty);
        }
        }
    }
    class Observer
    {
        public void HandleEvent(object sender, EventArgs args)
        {
            // upload the image to the online service
        }
    }