title: Use Task.Run instead of Delegate.BeginInvoke
body: <p>I have recently upgraded my projects to ASP.NET 4.5 and I have been waiting a long time to use 4.5's asynchronous capabilities. After reading the documentation I'm not sure whether I can improve my code at all.</p>
  
  <p>I want to execute a task asynchronously and then forget about it. The way that I'm currently doing this is by creating delegates and then using <code>BeginInvoke</code>.</p>
  
  <p>Here's one of the filters in my project with creates an audit in our database every time a user accesses a resource that must be audited:</p>
  
  <pre><code>public override void OnActionExecuting(ActionExecutingContext filterContext)
  {
      var request = filterContext.HttpContext.Request;
      var id = WebSecurity.CurrentUserId;
  
      var invoker = new MethodInvoker(delegate
      {
          var audit = new Audit
          {
              Id = Guid.NewGuid(),
              IPAddress = request.UserHostAddress,
              UserId = id,
              Resource = request.RawUrl,
              Timestamp = DateTime.UtcNow
          };
  
          var database = (new NinjectBinder()).Kernel.Get&lt;IDatabaseWorker&gt;();
          database.Audits.InsertOrUpdate(audit);
          database.Save();
      });
  
      invoker.BeginInvoke(StopAsynchronousMethod, invoker);
  
      base.OnActionExecuting(filterContext);
  }
  </code></pre>
  
  <p>But in order to finish this asynchronous task, I need to always define a callback, which looks like this:</p>
  
  <pre><code>public void StopAsynchronousMethod(IAsyncResult result)
  {
      var state = (MethodInvoker)result.AsyncState;
      try
      {
          state.EndInvoke(result);
      }
      catch (Exception e)
      {
          var username = WebSecurity.CurrentUserName;
          Debugging.DispatchExceptionEmail(e, username);
      }
  }
  </code></pre>
  
  <p>I would rather not use the callback at all due to the fact that I do not need a result from the task that I am invoking asynchronously.</p>
  
  <p>How can I improve this code with <code>Task.Run()</code> (or <code>async</code> and <code>await</code>)?</p>