【问题标题】:How do I invoke a method on the UI thread when using the TPL?使用 TPL 时如何调用 UI 线程上的方法?
【发布时间】:2011-09-06 17:59:10
【问题描述】:

我正在开发一个使用 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));

    ...
}

【问题讨论】:

    标签: mvvm task-parallel-library


    【解决方案1】:

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

    编辑: 我做了一个实用类。它是静态的,但如果你愿意,你可以为它创建一个接口并使其成为非静态的:

    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() );
    }
    

    【讨论】:

    • 这确实有效,我不得不说非常聪明。好一个!而且我认为它也比 Dispatcher.Invoke 更优雅
    • 在我的项目中,我有一个接口,多亏了它,我的代码也非常可测试。
    【解决方案2】:

    要将方法调用编组到主 UI 线程,您可以使用 Dispatcher 的 InvokeMethod 方法。如果你使用像 Carliburn 这样的 MVVM 框架,它对 Dispatcher 有抽象,所以你可以使用 Execute.OnUIThread(Action) 做几乎相同的事情。

    查看thisMicrosoft 关于如何使用 Dispatcher 的文章。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-24
      • 2019-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多