I recently upgraded my projects to ASP.NET 4.5, and I have been waiting for the use of asynchronous features 4.5. After reading the documentation, I'm not sure if I can improve my code at all.
I want to complete the task asynchronously, and then forget about it. The way I'm currently doing this is to create delegates and then use BeginInvoke .
Here, one of the filters in my project creates an audit in our database every time a user accesses a resource that needs to be checked:
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<IDatabaseWorker>(); database.Audits.InsertOrUpdate(audit); database.Save(); }); invoker.BeginInvoke(StopAsynchronousMethod, invoker); base.OnActionExecuting(filterContext); }
But in order to finish this asynchronous task, I need to always define a callback that looks like this:
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); } }
I would prefer not to use the callback at all because I don't need the result from the task that I call asynchronously.
How can I improve this code with Task.Run() (or async and await )?
source share