c# - WPF MVVM中用于数据库事务的任务,BackgroundWorkers或新线程?

标签 c# wpf mvvm task

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

最佳答案

您可以使用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);
}

关于c# - WPF MVVM中用于数据库事务的任务,BackgroundWorkers或新线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13974694/

相关文章:

c# - OSX 上的 Mono,Process.Start 有时会抛出无法处理的 native 包装器异常

c# - 使用 LINQ 将日期/周列表拆分为 a 和 b 周

wpf - 使用 PRISM 切换主视图

c# - 跳转到下一个标签

c# - 从另一个 View 模型调用 WPF 命令的 MVVM 方法是什么?

javascript - ExtJS 5.1.1 立即在 ViewModel 中触发绑定(bind)

c# - XAML 页面未在 Windows 10 Mobile 上的 WinRT 应用程序中被垃圾收集,但在 WP8.1 上按预期工作

c# - 获取声明类的名称?

wpf - 重新排序 WPF 数据网格列

c# - 为 xaml 中的第一列启用 DataGrid 排序