任务的比较.Status == RanToCompletion和task.IsCompleted

时间:2014-01-15 15:16:49

标签: c# async-await inotifytaskcompletion

考虑一下:

readonly INotifyTaskCompletion<Model> _modelAsync;
public INotifyTaskCompletion<Model> ModelAsync { get { return _modelAsync; } }
public ctor() // pseudo code
{
    _modelAsync = NotifyTaskCompletion.Create(GetModelAsync());
    _modelAsync.PropertyChanged += modelAsync_Ready;
}
async Task<Model> GetModelAsync()
    {
        var rv = await TaskEx.Run(new Func<Model>(() => Agent.GetModel());
        if (ModelAsync.IsSuccessfullyCompleted) Trace.WriteLine("after await completed");
        if (ModelAsync.Status != TaskStatus.RanToCompletion) Trace.WriteLine("after await not completed");
        if (ModelAsync.Result != null) Trace.WriteLine("after await result");
        if (ModelAsync.Result == null) Trace.WriteLine("after await no result");
        return rv;
 }
void modelAsync_Ready(object sender, PropertyChangedEventArgs e)
{
    if (e.PropertyName == "Result") { }// etc...
}

为什么在等待任务尚未完成之后呢? 我一直认为async-await模式的一大优点是:不再需要编写回调了!具有“正常程序”外观的异步编程。

但只有通过订阅propertyChanged(this, new PropertyChangedEventArgs("Result"));我才会收到结果通知 那是约。与编写回调或后台工作者相同的工作量。

1 个答案:

答案 0 :(得分:3)

您正在等待TaskEx.Run返回的任务,但是我没有尽可能地设置ModelAsync

假设ModelAsyncTask<Model>,那么也许你的意思是:

async Task<Model> GetModelAsync()
{
  ModelAsync = TaskEx.Run(...);
  await ModelAsync;
  // ModelAsync.IsCompleted is true here.
}

请注意,TaskTask<T>未实现INotifyPropertyChanged。如果您想要在任务完成时进行更新的数据绑定,请查看我的NotifyTaskCompletion type in the AsyncEx library