1

我有一个与数据库通信的小型 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();
}
4

2 回答 2

3

您可以使用async/ await,这将为您提供更自然的语法:

public static async Task RunAsync(Action backgroundWork, Action uiWork, Action<Exception> exceptionWork)
{
  try
  {
    // The time consuming work is run on a background thread.
    await Task.Run(backgroundWork);

    // The UI work is run on the UI thread.
    uiWork();
  }
  catch (Exception ex)
  {
    // Exceptions in the background task and UI work are handled on the UI thread.
    exceptionWork(ex);
  }
}

或者更好的是,只需替换RunAsync为代码本身,而不是

T[] values;
RunAsync(() => { values = GetDbValues(); }, () => UpdateUi(values), ex => UpdateUi(ex));

你可以说:

try
{
  var values = await Task.Run(() => GetDbValues());
  UpdateUi(values);
}
catch (Exception ex)
{
  UpdateUi(ex);
}
于 2012-12-20T15:37:30.010 回答
0

那么你可以使用任何这些技术。不过,我总是会在单独的线程上运行它们。重要的是线程操作在适当的时候被编组回 UI 线程。如果在 .net 4.5 中,我的偏好是使用任务或异步等待

于 2012-12-20T14:57:57.793 回答