22 May 2014

C# - Asynchronious methods with a callback

I thought this one up as a nice alternative to custom events: a method that does it's work asynchroniously and that invokes a callback method when it's done.

The method

public void GetMailBoxes(Action<Exception, List<MailBox>> method) {
  BackgroundWorker worker = new BackgroundWorker();
  worker.DoWork += (object sender, DoWorkEventArgs e) => {
    e.Result = Imap.Instance.GetMailBoxes();
  };
  worker.RunWorkerCompleted += (object sender, RunWorkerCompletedEventArgs e) => {
    method(e.Error, mMailBoxes);
  };
  worker.RunWorkerAsync();
}

Calling the method

account.GetMailBoxes((Exception ex, List mailBoxes) => {
  if (ex != null) {
    Program.Handle(ex);
  }
  else {
    lstMailBoxes.DataSource = mailBoxes;
  }
});

No comments:

Post a Comment