我正在寻找async / await中的一些最佳实践。 我有datepicker和observable集合,我想在异步更改的datetime上将数据加载到observable集合中。 我怎样才能修改我的代码来做到这一点,很好?我知道,属性不能是异步的。我知道命令,所以也许我需要在datepicker datetimechanged事件上绑定async命令?
public class LogViewModel : ViewModelBase
{
public LogViewModel()
{
LogCollection = new ObservableCollection<Log>();
DateTime = DateTime.Now.Date;
}
private DateTime _dateTime;
public DateTime DateTime
{
get { return _dateTime; }
set
{
if (_dateTime != value)
{
_dateTime = value;
LogCollection.Clear();
//long running code begins
using (var ctx = new DataContext())
{
ctx.Logs.Where(p => p.dt >= _dateTime && p.dt < _dateTime.AddDays(1))
.ToList().ForEach(z => LogCollection.Add(z));
}
RaisePropertyChanged("DateTime");
}
}
}
public ObservableCollection<Log> LogCollection { get; set; }
}
答案 0 :(得分:0)
我认为最佳做法是保持VM和类似的类清晰。所以我更喜欢在内部订阅PropertyChanged事件并将这样的逻辑移动到事件处理程序(重构友好示例):
public LogViewModel()
{
if (!DesignerProperties.IsInDesignTool)
{
PropertyChanged += HandlePropertyChanged;
}
}
private static string DateTimePropertyName = ExpressionHelper.NameOf((LogViewModel _) => _.DateTime);
private void HandlePropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == DateTimePropertyName)
{
//Start async operation in other thread via TPL Tasks/ThreadPool's QueueUserWorkItem etc. for example or using true-async IO operations (a bunch of real-async operations available in EF)
}
}