Mvvm 在使用TPL时,如何在UI线程上调用方法?

Mvvm 在使用TPL时,如何在UI线程上调用方法?,mvvm,task-parallel-library,Mvvm,Task Parallel Library,我正在开发一个MVVM应用程序,它使用TPL在后台执行多个任务。任务需要向UI报告进度,以便更新进度对话框。由于应用程序是MVVM,“进度”对话框绑定到名为“进度”的视图模型属性,该属性由带有签名的视图模型方法更新UpdateProgress(int increment)。后台任务需要调用此方法来报告进度 我使用一个方法来更新属性,因为它允许每个任务以不同的数量增加Progress属性。因此,如果我有两个任务,第一个任务的时间是第二个任务的四倍,那么第一个任务调用UpdateProgress(4

我正在开发一个MVVM应用程序,它使用TPL在后台执行多个任务。任务需要向UI报告进度,以便更新进度对话框。由于应用程序是MVVM,“进度”对话框绑定到名为“进度”的视图模型属性,该属性由带有签名的视图模型方法更新
UpdateProgress(int increment)
。后台任务需要调用此方法来报告进度

我使用一个方法来更新属性,因为它允许每个任务以不同的数量增加Progress属性。因此,如果我有两个任务,第一个任务的时间是第二个任务的四倍,那么第一个任务调用
UpdateProgress(4)
,第二个任务调用
UpdateProgress(1)
。因此,第一个任务完成时,进度为80%,第二个任务完成时,进度为100%

我的问题非常简单:如何从后台任务调用视图模型方法?代码如下。谢谢你的帮助


任务使用的代码如下所示的
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.";
    }
}
public void Execute(object parameter)
{
    ...

    // Background Task #2: Resequence files
    var secondTask = firstTask.ContinueWith(t => this.ResequenceFiles(fileList, progressDialogViewModel));

    ...
}

要处理对主UI线程的方法调用,可以使用Dispatcher的InvokeMethod方法。如果您使用像Carliburn这样的MVVM框架,它在Dispatcher上有抽象,因此您可以使用Execute.OnUIThread(Action)做几乎相同的事情


查看有关如何使用Dispatcher的Microsoft文章

假设您的ViewModel是在UI线程上构建的(即:通过视图或响应与视图相关的事件),这种情况几乎总是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() );
}
编辑: 我做了一个util类。它是静态的,但如果需要,可以为其创建一个接口并使其成为非静态的:

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.");
    }
}

这确实有效,我得说相当聪明。好的!我认为它也比Dispatcher更优雅。invoke在我的项目中,我有一个接口,多亏了它,我的代码也是非常可测试的。
void Something()
{
    UiDispatcher.Invoke( () => DoSomething() );
}