我有一个与数据库通信的小型 MVVM 应用程序。在完成后更新 UI 的后台线程中执行数据库事务的标准方法是什么(如果有)?我应该使用 BackgroundWorkers、TPL 还是实现自己的线程?目前我有一个静态类,具有以下后台工作方法:
public static void RunAsync(Action backgroundWork, Action uiWork, Action<Exception> exceptionWork) {
var uiContext = TaskScheduler.FromCurrentSynchronizationContext();
// The time consuming work is run on a background thread.
var backgroundTask = new Task(() => backgroundWork());
// The UI work is run on the UI thread.
var uiTask = backgroundTask.ContinueWith(_ => { uiWork(); },
CancellationToken.None,
TaskContinuationOptions.OnlyOnRanToCompletion,
uiContext);
// Exceptions in the background task are handled on the UI thread.
var exceptionTask = backgroundTask.ContinueWith(t => { exceptionWork(t.Exception); },
CancellationToken.None,
TaskContinuationOptions.OnlyOnFaulted,
uiContext);
// Exceptions in the UI task are handled on on the UI thread.
var uiExceptionTask = uiTask.ContinueWith(t => { exceptionWork(t.Exception); },
CancellationToken.None,
TaskContinuationOptions.OnlyOnFaulted,
uiContext);
backgroundTask.Start();
}