Dav*_*man 4 mvvm task-parallel-library
我正在开发一个MVVM应用程序,它使用TPL在后台执行几项任务.任务需要向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.";
}
}
Run Code Online (Sandbox Code Playgroud)
该声明viewModel.IncrementProgressCounter(1)不是抛出异常,但它没有通过主线程.从MVVM ICommand对象调用任务,代码如下所示:
public void Execute(object parameter)
{
...
// Background Task #2: Resequence files
var secondTask = firstTask.ContinueWith(t => this.ResequenceFiles(fileList, progressDialogViewModel));
...
}
Run Code Online (Sandbox Code Playgroud)
假设您的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());
}
Run Code Online (Sandbox Code Playgroud)
然后,当您收到活动时,您可以使用它来整理它:
void Something()
{
uiFactory.StartNew( () => DoSomething() );
}
Run Code Online (Sandbox Code Playgroud)
编辑: 我做了一个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.");
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
void Something()
{
UiDispatcher.Invoke( () => DoSomething() );
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1666 次 |
| 最近记录: |