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. [Angular Unit Testing] Shallow Pipe Testing

    import { TestBed, ComponentFixture } from '@angular/core/testing'; import { BrowserDynamicTestingMod ...

  2. [Angular Unit Testing] Testing Pipe

    import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'filesize' }) export class FileSi ...

  3. ArcEngine中最短路径的实现

    原文 ArcEngine中最短路径的实现 最短路径分析属于ArcGIS的网络分析范畴.而ArcGIS的网络分析分为两类,分别是基于几何网络和网络数据集的网络分析.它们都可以实现最短路径功能.下面先介绍 ...

  4. IDEA 多线程Debug

    一.问题描述 在idea中的进行调试时,代码中有多线程,想对线程中的代码进行跟踪,代码如下: for (int i = 0; i < 5; i++) { final int index = i; ...

  5. 【u216】A+B Problem(aplusb)

    Time Limit: 1 second Memory Limit: 128 MB [问题描述] 对于给定的A和B,求A+B的值. [输入格式] 输入文件aplusb.in的第1行为一个整数A,第2行 ...

  6. 【z03】Mayan游戏

    [问题描述] Mayan puzzle是最近流行起来的一个游戏.游戏界面是一个 7 行5 列的棋盘,上面堆放 着一些方块,方块不能悬空堆放,即方块必须放在最下面一行,或者放在其他方块之上.游 戏通关是 ...

  7. windows 下使用 virtualenv 创建虚拟环境

    virtualenv虚拟环境为每个项目隔离了一套运行类库,不同的项目在各自的虚拟环境中使用不同的类库,避免了将所有类库都安装到系统环境中导致的不同项目需要不同(版本)类库的问题,项目与项目之间的类库依 ...

  8. 动态备份SQL-SERVER数据库——SQLDMO

    转载:http://www.cnblogs.com/liulanglang/archive/2007/12/04/981812.html 上周要写一个SQL-SERVER数据库备份还原的程序,很没有思 ...

  9. telnet 的使用(ping 与 telnet)

    基本用法 >> telnet localhost 23 // 23 表示 telnet 服务的端口号,不写端口号也可以,telnet 默认绑定的端口号就是 23 // netstat -a ...

  10. C# 7.0 使用下划线忽略使用的变量

    原文:C# 7.0 使用下划线忽略使用的变量 版权声明:博客已迁移到 http://lindexi.gitee.io 欢迎访问.如果当前博客图片看不到,请到 http://lindexi.gitee. ...