我正在开发一个使用 TPL 在后台执行多个任务的 MVVM 应用程序。任务需要向 UI 报告进度,以便可以更新进度对话框。由于应用程序是 MVVM,因此进度对话框绑定(bind)到名为 Progress 的 View 模型属性,该属性由带有签名 UpdateProgress(int increment)
的 View 模型方法更新.后台任务需要调用该方法上报进度。
我使用一种方法来更新属性,因为它允许每个任务将 Progress 属性增加不同的数量。所以,如果我有两个任务,第一个任务的时间是第二个的四倍,第一个任务调用 UpdateProgress(4)
,第二个任务调用 UpdateProgress(1)
.因此,第一个任务完成时进度为 80%,第二个任务完成时进度为 100%。
我的问题非常简单:如何从后台任务中调用 View 模型方法?代码如下。谢谢你的帮助。
任务使用 Parallel.ForEach()
,在如下代码中:
private void ResequenceFiles(IEnumerable<string> fileList, ProgressDialogViewModel viewModel)
{
// Wrap token source in a Parallel Options object
var loopOptions = new ParallelOptions();
loopOptions.CancellationToken = viewModel.TokenSource.Token;
// Process images in parallel
try
{
Parallel.ForEach(fileList, loopOptions, sourcePath =>
{
var fileName = Path.GetFileName(sourcePath);
if (fileName == null) throw new ArgumentException("File list contains a bad file path.");
var destPath = Path.Combine(m_ViewModel.DestFolder, fileName);
SetImageTimeAttributes(sourcePath, destPath);
// This statement isn't working
viewModel.IncrementProgressCounter(1);
});
}
catch (OperationCanceledException)
{
viewModel.ProgressMessage = "Image processing cancelled.";
}
}
声明
viewModel.IncrementProgressCounter(1)
没有抛出异常,但它没有进入主线程。从 MVVM ICommand
调用任务对象,代码如下所示:public void Execute(object parameter)
{
...
// Background Task #2: Resequence files
var secondTask = firstTask.ContinueWith(t => this.ResequenceFiles(fileList, progressDialogViewModel));
...
}
最佳答案
假设您的 ViewModel 是在 UI 线程上构建的(即:由 View 或响应 View 相关事件),这几乎总是 IMO 的情况,您可以将其添加到您的构造函数中:
// Add to class:
TaskFactory uiFactory;
public MyViewModel()
{
// Construct a TaskFactory that uses the UI thread's context
uiFactory = new TaskFactory(TaskScheduler.FromCurrentSynchronizationContext());
}
然后,当你得到你的事件时,你可以使用它来编码它:
void Something()
{
uiFactory.StartNew( () => DoSomething() );
}
编辑:
我做了一个实用类。它是静态的,但如果您愿意,可以为它创建一个接口(interface)并使其成为非静态的:
public static class UiDispatcher
{
private static SynchronizationContext UiContext { get; set; }
/// <summary>
/// This method should be called once on the UI thread to ensure that
/// the <see cref="UiContext" /> property is initialized.
/// <para>In a Silverlight application, call this method in the
/// Application_Startup event handler, after the MainPage is constructed.</para>
/// <para>In WPF, call this method on the static App() constructor.</para>
/// </summary>
public static void Initialize()
{
if (UiContext == null)
{
UiContext = SynchronizationContext.Current;
}
}
/// <summary>
/// Invokes an action asynchronously on the UI thread.
/// </summary>
/// <param name="action">The action that must be executed.</param>
public static void InvokeAsync(Action action)
{
CheckInitialization();
UiContext.Post(x => action(), null);
}
/// <summary>
/// Executes an action on the UI thread. If this method is called
/// from the UI thread, the action is executed immendiately. If the
/// method is called from another thread, the action will be enqueued
/// on the UI thread's dispatcher and executed asynchronously.
/// <para>For additional operations on the UI thread, you can get a
/// reference to the UI thread's context thanks to the property
/// <see cref="UiContext" /></para>.
/// </summary>
/// <param name="action">The action that will be executed on the UI
/// thread.</param>
public static void Invoke(Action action)
{
CheckInitialization();
if (UiContext == SynchronizationContext.Current)
{
action();
}
else
{
InvokeAsync(action);
}
}
private static void CheckInitialization()
{
if (UiContext == null) throw new InvalidOperationException("UiDispatcher is not initialized. Invoke Initialize() first.");
}
}
用法:
void Something()
{
UiDispatcher.Invoke( () => DoSomething() );
}
关于mvvm - 使用 TPL 时如何在 UI 线程上调用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7324123/