【发布时间】:2021-01-18 22:42:19
【问题描述】:
经过:
和
How to bind WPF button to a command in ViewModelBase?
我想出了以下异步(或同步?)读取文件内容并将其呈现到窗口的代码:
class AppliedJobsViewModel
{
private TexParser texParser;
private ICommand _openTexClick;
public ICommand OpenTexClick
{
get
{
return _openTexClick ?? (_openTexClick = new CommandHandler(() => ReadAndParseTexFile(), () => CanExecute));
}
}
public bool CanExecute
{
get
{
// check if executing is allowed, i.e., validate, check if a process is running, etc.
return true;
}
}
public async Task ReadAndParseTexFile()
{
if (texParser == null)
{
texParser = new TexParser();
}
// Read file asynchronously here
await ReadAndParseTexFileAsync();
string[][] appliedJobs = texParser.getCleanTable();
}
private async Task ReadAndParseTexFileAsync()
{
texParser.ReadTexFile();
await Task.Delay(100);
}
public ObservableCollection<AppliedJob> AppliedJobs {
get;
set;
}
}
哪个“有效”,但我不喜欢 Task.Delay(100)(恒定等待时间)。
VS 也在线告诉我:
return _openTexClick ?? (_openTexClick = new CommandHandler(() => ReadAndParseTexFile(), () => CanExecute));
“因为没有等待这个调用,所以在调用完成之前这个方法的执行还在继续”。
但是这种方法将代码绑定到 wpf 视图。默认不是异步的吗?
【问题讨论】:
-
CommandHandler是什么? -
一个路由点击(或任何形式的用户交互)的类。取自(复制)自stackoverflow.com/questions/12422945/…
-
看来
CommandHandler只是实现了ICommand类似中继命令的接口。它同时执行传递的Action。要进行异步执行,您可以使用 async relay command 或在 xaml 中设置IsAsync -
谢谢!我会试一试。你知道Task.Delay(100);的方法吗?
-
我认为没有理由在代码中使用
await Task.Delay(100)。如果您需要一些延迟,绑定中有Delay属性
标签: c# wpf multithreading asynchronous async-await