我有这样的方法
public void LoadProgrammeListFromChannel(TVDailyScheduleParam scheduleParam, Action callback)
{
string url = Helper.GetProgrammeUrl(scheduleParam.Day, scheduleParam.Channel.Id); //1//
WebClient client = new WebClient(); //2//
client.OpenReadCompleted += new OpenReadCompletedEventHandler((sender, e) => //3//
{//5//
if (e.Error != null)
return;
try
{
_programmeList.Clear();
_programmeList = DataService.GetProgrammeList(e.Result);
// call method in MainVM to update View
callback();
}
finally
{
// close file stream
e.Result.Close();
}
});
client.OpenReadAsync(new Uri(url, UriKind.Absolute)); //4//
}
我有这样的照片
LoadWhatsonProgrammeCommand = new RelayCommand(()=>
{
foreach (TVDailyScheduleParam param in _tvDailyScheduleVM.ChannelList.Select(c => new TVDailyScheduleParam(DateTime.Today, c, false)))
{
TVDailyScheduleParam param2 = param;
_tvDailyScheduleVM.LoadProgrammeListFromChannel(param2, ()=>
{
RaisePropertyChanged(TV_DAILY_SCHEDULE_VM);
});
_tvDailyScheduleVM.GetWhatsonProgramme(param2, ()=>
{
RaisePropertyChanged(TV_DAILY_SCHEDULE_VM);
});
}
});
现在我调用命令时。首先,它运行_tvDailyScheduleVM.LoadProgrammeListFromChannel
并调用LoadProgrammeListFromChannel
方法。
在LoadProgrammeListFromChannel
方法中,它从1开始运行 - > 2 - > 3.在3,它没有完成,它运行到4然后回到命令并继续运行_tvDailyScheduleVM.GetWhatsonProgramme
。
但_programmeList in LoadProgrammeListFromChannel
未更新,因此GetWhatsonProgramme
无法准确运行。
如何在运行LoadProgrammeListFromChannel
之前返回_programmeList
以运行3更新_tvDailyScheduleVM.GetWhatsonProgramme
?
答案 0 :(得分:0)
您描述的行为是“按设计”。您的方法LoadProgrammeListFromChannel
进行异步调用。这意味着在您的方法中,序列是1 - > 2 - > 3 - > 4 - >返回 - >在调用函数中执行代码 - >那么晚些时候5然后回调。
结果LoadProgrammeListFromChannel
和GetWhatsonProgramme
并行执行。因此,如果GetWhatsonProgramme
需要始终才能在LoadProgrammeListFromChannel
之后运行,您将有权将GetWhatsonProgramme
移至您的回调方法中,即
LoadWhatsonProgrammeCommand = new RelayCommand(()=> {
var channelList = _tvDailyScheduleVM
.ChannelList
.Select(c => new TVDailyScheduleParam(
DateTime.Today,
c,
false
));
foreach (TVDailyScheduleParam param in channelList) {
TVDailyScheduleParam param2 = param;
_tvDailyScheduleVM.LoadProgrammeListFromChannel(param2, ()=> {
RaisePropertyChanged(TV_DAILY_SCHEDULE_VM);
_tvDailyScheduleVM.GetWhatsonProgramme(param2, ()=> {
RaisePropertyChanged(TV_DAILY_SCHEDULE_VM);
});
});
}
});
或者,您可以订阅ViewModel的PropertyChangedEvent,如果TV_DAILY_SCHEDULE_VM
属性已更改,请从那里调用GetWhatsonProgramme
,尽管这可能不太合适。