Use Task.Run instead of Delegate.BeginInvoke

后端 未结 3 430
被撕碎了的回忆
被撕碎了的回忆 2021-02-06 08:11

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 wh

3条回答
  •  有刺的猬
    2021-02-06 08:39

    If I understood your requirements correctly, you want to kick off a task and then forget about it. When the task completes, and if an exception occurred, you want to log it.

    I'd use Task.Run to create a task, followed by ContinueWith to attach a continuation task. This continuation task will log any exception that was thrown from the parent task. Also, use TaskContinuationOptions.OnlyOnFaulted to make sure the continuation only runs if an exception occurred.

    Task.Run(() => {
        var audit = new Audit
            {
                Id = Guid.NewGuid(),
                IPAddress = request.UserHostAddress,
                UserId = id,
                Resource = request.RawUrl,
                Timestamp = DateTime.UtcNow
            };
    
        var database = (new NinjectBinder()).Kernel.Get();
        database.Audits.InsertOrUpdate(audit);
        database.Save();
    
    }).ContinueWith(task => {
        task.Exception.Handle(ex => {
            var username = WebSecurity.CurrentUserName;
            Debugging.DispatchExceptionEmail(ex, username);
        });
    
    }, TaskContinuationOptions.OnlyOnFaulted);
    

    As a side-note, background tasks and fire-and-forget scenarios in ASP.NET are highly discouraged. See The Dangers of Implementing Recurring Background Tasks In ASP.NET

提交回复
热议问题