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

时间:2011-09-06 17:59:10

标签: mvvm task-parallel-library

我正在开发一个使用TPL在后台执行多项任务的MVVM应用程序。任务需要向UI报告进度,以便可以更新进度对话框。由于应用程序是MVVM,因此进度对话框绑定到名为Progress的视图模型属性,该属性由具有签名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.";
    }
}

声明viewModel.IncrementProgressCounter(1)不会抛出异常,但它没有通过主线程。这些任务是从MVVM ICommand对象调用的,代码如下所示:

public void Execute(object parameter)
{
    ...

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

    ...
}

2 个答案:

答案 0 :(得分:9)

假设您的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() );
}

修改 我做了一个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.");
    }
}

用法:

void Something()
{
    UiDispatcher.Invoke( () => DoSomething() );
}

答案 1 :(得分:2)

要对主UI线程进行方法调用,可以使用Dispatcher的InvokeMethod方法。如果您使用像Carliburn这样的MVVM框架,它会对Dispatcher进行抽象,因此您可以使用Execute.OnUIThread(Action)执行几乎相同的操作。

检查this Microsoft有关如何使用Dispatcher的文章。