【发布时间】:2022-07-12 01:07:35
【问题描述】:
我正在使用 VSTO 和 WPF (MVVM) 为 C# 中的 Word 开发一个搜索工具。
我正在使用 Microsoft.Office.Interop.Word.Find() 方法并遍历文档以查找匹配项。我需要处理的一些文档超过 300,000 个字符,因此搜索可能需要 10 多秒。我想为我的用户提供取消操作的选项。
我面临的问题是,取消长时间运行的操作的按钮无法访问,因为 UI/主线程由于 Find 操作触发编组回主线程而保持忙碌 - 中继命令是从未触发。我的数据绑定是正确的,并且已经使用不使用 UI/主线程的长时间运行的操作测试了按钮。
public class SmartFindViewModel : BindableBase
{
ctor()
{
FindCommand = new RelayCommand(o => Find(), o => CanFindExecute());
}
private async void Find()
{
var token = cancellationTokenSource.Token;
**Update user here and show progress view**
try
{
await System.Threading.Tasks.Task.Run(async() => {
var searchResults = await SearchRange(token);
System.Windows.Application.Current.Dispatcher.Invoke(() =>
{
**Update results on UI Thread**
});
return;
}
});
}
catch (OperationCanceledException)
{
...
}
catch(Exception ex)
{
...
}
finally
{
**Hide progress view**
}
}
public async Task<List<SmartFindResultViewModel>> SearchRange(CancellationToken cancellationToken)
{
** Get Word range**
await System.Threading.Tasks.Task.Run(() =>
{
do
{
range.Find.Execute();
if (!range.Find.Found) return;
**
} while (range.Find.Found && !cancellationToken.IsCancellationRequested);
});
return Results;
}
}
我的问题很简单,如果 UI 线程通过互操作方法保持忙碌,如何允许按钮保持操作?还是只是 VSTO 的限制或我的代码有问题?
【问题讨论】:
标签: c# wpf vsto office-interop office-addins