TPL 异常 - 如何附加到主线程

TPL Exception - How to attach to the main thread

我计划在我现有的 asp.net 应用程序中实施 TPL 以提高性能。 我在有选择的地方实现它们(比如调用将数据写入一个 table 和某种不相关的非同步操作),我们正在处理 application_error 事件中的所有未处理异常global.asax 文件。

但是当我收到错误时,TPL 不会将该错误抛给 application_error 事件。 当我尝试使用 Task.WaitAll(t1) 时,它会抛出 app_error 事件,但它需要一段时间来处理编写的代码。 但是当我尝试使用以下方法时(仅在发生故障时需要一些时间)然后它也不会向主线程抛出异常。

  Task.Factory.StartNew(Sub(mainContext)
                                      HttpContext.Current = mainContext
                                      LookUpRepository.AddItems(CurrentContext.LoggedInUser.UserID, ClientID)
                                  End Sub, HttpContext.Current).ContinueWith(Sub(tplException)
                                                                                 For Each ex In tplException.Exception.InnerExceptions
                                                                                     Throw ex
                                                                                 Next

                                                                             End Sub, TaskContinuationOptions.OnlyOnFaulted Or TaskContinuationOptions.ExecuteSynchronously)

我尝试使用 ConcurrentQueue 来捕获异常,有时它会停止应用程序并且控件不会继续执行进一步的代码行。

那么我如何才能将 TPL exceotion 附加到托管 asp.net 应用程序的主线程。

.Net 中有一个可用的可观察集合 ObservableCollection。如果我们打开的线程中有错误,如果我们将它们添加到这个 ObservableCollection 中,那么它会引发一个事件,我们可以从那个事件中处理这个错误

 Task.Factory.StartNew(Sub(mainContext)
                                  'Using sw As StreamWriter = File.AppendText("c:/logs/t7.txt")
                                  '    sw.WriteLine("thread=" + Thread.CurrentThread.ManagedThreadId.ToString())
                                  'End Using
                                  HttpContext.Current = mainContext
                                  'Do some operation
                                 End Sub, HttpContext.Current).ContinueWith(Sub(tplException, subContext)
                                                                             HttpContext.Current = subContext
                                                                             If IsNothing(tplException.Exception) Then Exit Sub
                                                                             For Each ex In tplException.Exception.InnerExceptions
                                                                                 MyAppState.Instance.ObservableException.Add(ex)
                                                                             Next

                                                                         End Sub, HttpContext.Current)

集合需要申报

 Public WithEvents ObservableException As ObservableCollection(Of Exception)

.Net 框架将引发的事件以处理异常

Private Sub CollectionChangedHandler(sender As Object, e As NotifyCollectionChangedEventArgs) Handles ObservableException.CollectionChanged
    Dim ex = DirectCast(e.NewItems(0), Exception)
    ExceptionLog.SaveFile(ExceptionLog.ReadExceptionInformationFromException(ex))
End Sub