Call async methods with C#

Posted by Andrea on 2009-10-15 10:50
Suppose you have the following method
public void UploadFile(string path)
{
    try
    {
        //... uploads the file to the server
    }
    catch(Exception ex)
    {
        // ... error handling
    }
}

Suppose you are using it in a web service, your requirement is to give an immediate response, but you also need to upload the file asynchronously (the file resides on the server) , the user won't consume it soon, he/she only needs the upload.

1) Declare a method delegate, eg:
  public delegate void UploadFileDelegate(string path);

2) Invoke it properly
  [WebMethod]
  public bool GetFile(string path)
  {
      try
      {
          UploadFileDelegate uid = UploadFile;
          IAsyncResult rsl = uid.BeginInvoke(path, null, null);
          return true;
      }
      catch(Exception ex)
      {
          return false;
      }
  }

This will help you to launch a bunch of operations without being unresponsive, you can implement error notifications of course, you can poll, or wait for the procedure to complete at a certain point,  launch multithreaded tasks... and so on.