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スレッドにマーシャリングされることです。私の好みは、タスクを使用するか、.net4.5の場合は非同期待機することです

于 2012-12-20T14:57:57.793 に答える