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. ant脚本中设置环境变量

    http://blog.csdn.net/quqi99/article/details/5329841

  2. [Grid Layout] Describe a grid layout using grid-template-areas

    We can describe the nature of a grid in an ‘ASCII-art’ way with grid-template-areas. Let’s see how t ...

  3. Erlang中的record与宏

    http://www.cnblogs.com/me-sa/archive/2011/07/20/erlang0006.html 在Erlang中使用Tuple ,数据项的顺序\数量都是确定的,一旦数据 ...

  4. Expression Blend 的点滴(1)--ListBox华丽大变身

    原文:Expression Blend 的点滴(1)--ListBox华丽大变身 最近,在园子里有不少朋友写了关于Blend的优秀并且实用的文章,在此,我先代表silverlight的爱好者感谢他们的 ...

  5. ITFriend创业败局(三):技术人员创业,需要尽可能避免,或者需要解决的5个重要问题

    一.插科打诨: 本想给小雷粉,做一个创业"成功案例"的,结果做成了一个"反面教材"~ No zuo,no die~ 二.写作目的:分享自己作为一名技术人员,或者 ...

  6. Tricks(四十七)—— 布尔矩阵(0-1矩阵)取反

    假定 X 是一个 0-1 元素构成的布尔矩阵,则对其取反,0 变成 1,1 变为 0(True 变为 False,False 变成 True),只需要一步简单的操作: Y = (X == False)

  7. solr 7.x 查询及高亮

    查询时的api分为两种一种是万能的set,还有一种是setxxxquery @Test public void search2() throws Exception{ HttpSolrClient s ...

  8. solr 7.x 配置ikanalyzer

    一.使用支持高版本的ikanalzyer进行分词配置(尾部有文件链接) ikanalyzer最后更新是在2012年,对于高版本的lucee不支持.但网上还是有被修改过的Ikanalyzer的6.5.0 ...

  9. Android Studio 如何打JAR包(修订版)

    AndroidStudio项目打包成jar 前言:在eclipse中我们知道如何将一个项目导出为jar包,现在普遍AndroidStuido开发,这里一步一步详加介绍AS项目打包成jar,jar和ar ...

  10. Git命令小总结

    常用 git init git 初始化 git clone https://github.com/wsxx111/thisStudy.git 从远端拉下来 git status 查看跟踪状态 git ...