C# custom event handling for download complete

vivekj2004
vivekj2004 used Ask the Experts™
on
1. If I want to write code in C# where when data coming from a webservice is completed, an event (custom event) is triggered. So I can perform certain events when data download is complete.
2. Another peice of code is where I'm loading the data on a control, and I want to trigger a custom made event when data is complete for display.

This will need registering of delegates. Is there a scenario, where we would unregister an event or delegate (what would be the purpose of doing that?)
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Commented:
Think of event registration as listening for a signal.  Consider a "Notifying" diagnostic event that sends a string of internal status messages.  You could register a function to this event that writes the strings to a text box when a user clicks a "Enable Diagnostics".  But what about when they what to stop the messages.  You could simply unregister the function (the "-=" operator) when the "Disable Diagnostics" button was clicked.

Author

Commented:
Thanks for the explanation. Can I get an example where data download completion triggers an event?
Commented:
public class YourClass
{
  //custom event args class for passing info to the event
  public class DownloadEventArgs : EventArgs{
    public Int32 DownloadBytes{get; set;}
  }

  public event EventHandler<DownloadEventArgs> DownloadCompleted;
  protected void OnDownloadCompleted(DownloadEventArgs e)
  {
    //check to see if anybody's listening...
    if( DownloadCompleted != null )
    {
      DownloadCompleted(this, e);
    }
  }

  public void YourDownloadFunction()
  {
    Int32 downloadBytes = 0;
    //your download code here
    DownloadEventArgs dea = new DownloadEventArgs(){DownloadBytes = downloadBytes};
    OnDownloadCompleted(dea);

  }
}

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial