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