using System;
using System.ComponentModel;
using System.Threading.Tasks;
public sealed class NotifyTaskCompletion<TResult> : INotifyPropertyChanged
{
public NotifyTaskCompletion(Task<TResult> task)
{
Task = task;
if (!task.IsCompleted)
{
var _ = WatchTaskAsync(task);
}
}
private async Task WatchTaskAsync(Task task)
{
try
{
await task;
}
catch
{
}
var propertyChanged = PropertyChanged;
if (propertyChanged == null)
return;
propertyChanged(this, new PropertyChangedEventArgs("Status"));
propertyChanged(this, new PropertyChangedEventArgs("IsCompleted"));
propertyChanged(this, new PropertyChangedEventArgs("IsNotCompleted"));
if (task.IsCanceled)
{
propertyChanged(this, new PropertyChangedEventArgs("IsCanceled"));
}
else if (task.IsFaulted)
{
propertyChanged(this, new PropertyChangedEventArgs("IsFaulted"));
propertyChanged(this, new PropertyChangedEventArgs("Exception"));
propertyChanged(this,
new PropertyChangedEventArgs("InnerException"));
propertyChanged(this, new PropertyChangedEventArgs("ErrorMessage"));
}
else
{
propertyChanged(this,
new PropertyChangedEventArgs("IsSuccessfullyCompleted"));
propertyChanged(this, new PropertyChangedEventArgs("Result"));
}
}
public Task<TResult> Task { get; private set; }
public TResult Result { get { return (Task.Status == TaskStatus.RanToCompletion) ?
Task.Result : default(TResult); } }
public TaskStatus Status { get { return Task.Status; } }
public bool IsCompleted { get { return Task.IsCompleted; } }
public bool IsNotCompleted { get { return !Task.IsCompleted; } }
public bool IsSuccessfullyCompleted { get { return Task.Status ==
TaskStatus.RanToCompletion; } }
public bool IsCanceled { get { return Task.IsCanceled; } }
public bool IsFaulted { get { return Task.IsFaulted; } }
public AggregateException Exception { get { return Task.Exception; } }
public Exception InnerException { get { return (Exception == null) ?
null : Exception.InnerException; } }
public string ErrorMessage { get { return (InnerException == null) ?
null : InnerException.Message; } }
public event PropertyChangedEventHandler PropertyChanged;
}

An updated ViewModel using NotifyTaskCompletion<T> would look like this:

 public class MainViewModel
{
public MainViewModel()
{
UrlByteCount = new NotifyTaskCompletion<int>(
MyStaticService.CountBytesInUrlAsync("http://www.example.com"));
}
public NotifyTaskCompletion<int> UrlByteCount { get; private set; }
}
 <Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Window.Resources>
<BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>
</Window.Resources>
<Grid>
<!-- Busy indicator -->
<Label Content="Loading..." Visibility="{Binding UrlByteCount.IsNotCompleted,
Converter={StaticResource BooleanToVisibilityConverter}}"/>
<!-- Results -->
<Label Content="{Binding UrlByteCount.Result}" Visibility="{Binding
UrlByteCount.IsSuccessfullyCompleted,
Converter={StaticResource BooleanToVisibilityConverter}}"/>
<!-- Error details -->
<Label Content="{Binding UrlByteCount.ErrorMessage}" Background="Red"
Visibility="{Binding UrlByteCount.IsFaulted,
Converter={StaticResource BooleanToVisibilityConverter}}"/>
</Grid>
</Window>

From: https://msdn.microsoft.com/en-us/magazine/dn605875.aspx

Call asynchronous method in constructor的更多相关文章

  1. Asynchronous method in while loop 构造异步调用链

    Asynchronous method in while loop https://stackoverflow.com/questions/43064719/javascript-asynchrono ...

  2. 【反射】Reflect Class Field Method Constructor

    关于反射 Reflection 面试题,什么是反射(反射的概念)? 主要是指程序可以访问,检测和修改它本身状态或行为的一种能力,并能根据自身行为的状态和结果,调整或修改应用所描述行为的状态和相关的语义 ...

  3. Async/Await - Best Practices in Asynchronous Programming z

    These days there’s a wealth of information about the new async and await support in the Microsoft .N ...

  4. 【C#】转一篇MSDN杂志文:ASP.NET Pipeline: Use Threads and Build Asynchronous Handlers in Your Server-Side Web Code

    序:这是一篇发表在2003年6月刊的MSDN Magazine的文章,现在已经不能在线阅读,只提供chm下载.讲的是异步请求处理那些事,正是我上一篇博文涉及的东西(BTW,事实上这篇杂志阐述了那么搞然 ...

  5. JAVA深入研究——Method的Invoke方法。

    在写代码的时候,发现Method可以调用子类的对象,但子类即使是改写了的Method,方法名一样,去调用父类的对象也会报错,虽然这是很符合多态的现象,也符合java的动态绑定规范,但还是想弄懂java ...

  6. Event-based Asynchronous Pattern Overview基于事件的异步模式概览

    https://msdn.microsoft.com/zh-cn/library/wewwczdw(v=vs.110).aspx Applications that perform many task ...

  7. Task-based Asynchronous Pattern (TAP)

    The Task-based Asynchronous Pattern (TAP) is based on the System.Threading.Tasks.Task and System.Thr ...

  8. JAVA深入研究——Method的Invoke方法

    http://www.cnblogs.com/onlywujun/p/3519037.html 在写代码的时候,发现Method可以调用子类的对象,但子类即使是改写了的Method,方法名一样,去调用 ...

  9. Java 反射机制[Method反射]

    Java 反射机制[Method反射] 接着上一篇Java 反射机制[Field反射],通过调用Person类的setName方法将obj的name字段的Value设置为"callPerso ...

随机推荐

  1. MQ选型对比RabbitMQ RocketMQ ActiveMQ

    原文:MQ选型对比RabbitMQ RocketMQ ActiveMQ 几种MQ产品说明:     ZeroMQ :  扩展性好,开发比较灵活,采用C语言实现,实际上他只是一个socket库的重新封装 ...

  2. 【9107】Hanoi双塔问题(NOIP2007)

    Time Limit: 10 second Memory Limit: 2 MB 问题描述 给定A,B,C三根足够长的细柱,在A柱上放有2n个中间有孔的圆盘,共有n个不同的尺寸,每个尺寸都有两个相同的 ...

  3. 删除vector中的重复数据(unique)

    #include <iostream> #include <vector> #include <algorithm> #include <assert.h&g ...

  4. ios开发总结,日常开发:ios开发功能收集,经验分享等等(不断更新中。。。)

    github资料学习和下载地址:https://github.com/niexiaobo/MyDailyDevelopmentNotes ios 学习模块 ios APP 日志管理的重要性: 一个功能 ...

  5. [转] Valgrind使用

    http://www.cnblogs.com/napoleon_liu/articles/2001802.html 调不尽的内存泄漏,用不完的Valgrind Valgrind 安装 1. 到www. ...

  6. [.NET Core 24]把project.json迁移到.csproj

    链接:https://blog.jetbrains.com/dotnet/2017/04/04/rider-eap-update-csproj-based-net-core-support-migra ...

  7. erlang app 文件

    http://hje.iteye.com/blog/1211734 应用的概念¶ 当我们写了实现特定功能的代码之后,我们可能想将代码转成一个 应用 (application),这是可以作为一个单元启动 ...

  8. Python采用struct处理二进制

    有时需要使用python二进制数据,实例,件.socket操作时.这时候.能够使用python的struct模块来完毕.能够用 struct来处理c语言中的结构体. struct模块中最重要的三个函数 ...

  9. Android开发者的演示工具——asm.jar

    作为Android开发者,我们有时候需要给客户或者其他人演示我们的Android作品.我们可以使用类似豌豆荚.360手机助手这样的软件,今天我来介绍一个Android开发者的演示工具--asm.jar ...

  10. PCI GXL学习之安装篇

    作者:朱金灿 来源:http://blog.csdn.net/clever101 上周简单学习了PCI gxl的使用和二次开发.说实话gxl没有我想象中那么自动化,我原以为把一个数据处理作业扔给gxl ...