博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Async callback to awaitable Task<> z
阅读量:2238 次
发布时间:2019-05-09

本文共 1706 字,大约阅读时间需要 5 分钟。

http://blog.tedd.no/2013/09/13/async-callback-to-awaitable-task/

 

The Async-Await feature in .Net is really super. At least until it comes to debugging, exception handling and race conditions. In short it cuts down on code, bugs, complexity and allows for linear programming. Traditional async programming uses callbacks (events) that adds to code complexity, it also forces an unnatural break in your code.

Luckily more and more .Net-objects is getting support for async-await, and the most important ones are already implemented.

However, there is also a very easy way to convert a traditional async into async-await. In the sample code below I have made an awaitable task out of the camera for WP7, but this can be applied to any async callback.

public static Task
TakePicture(){ var taskCompletionSource = new TaskCompletionSource
(); var cameraCaptureTask = new CameraCaptureTask(); cameraCaptureTask.Completed += (sender, result) => taskCompletionSource.SetResult(result); cameraCaptureTask.Show(); return taskCompletionSource.Task;}
  1. Create a TaskCompletionSource with return type.
  2. Set up your traditional async, but in the callback (done) event pass result on to TaskCompletionSource.
  3. Return TaskCompletionSource.Task to waiting method.

To use this code simply:

private void DoPostButton_Click(object sender, RoutedEventArgs e){    DoWhateverWithCamera();}public async void DoWhateverWithCamera(){    var result = await TakePicture();   // Now do something with the result}

This will not block GUI-thread, but return result on it. No need to use Dispatcher, dedicated background thread or async callback.

转载于:https://www.cnblogs.com/zeroone/p/3648315.html

你可能感兴趣的文章
flask_migrate
查看>>
解决activemq多消费者并发处理
查看>>
UDP连接和TCP连接的异同
查看>>
hibernate 时间段查询
查看>>
java操作cookie 实现两周内自动登录
查看>>
Tomcat 7优化前及优化后的性能对比
查看>>
Java Guava中的函数式编程讲解
查看>>
Eclipse Memory Analyzer 使用技巧
查看>>
tomcat连接超时
查看>>
谈谈编程思想
查看>>
iOS MapKit导航及地理转码辅助类
查看>>
检测iOS的网络可用性并打开网络设置
查看>>
简单封装FMDB操作sqlite的模板
查看>>
iOS开发中Instruments的用法
查看>>
强引用 软引用 弱引用 虚引用
查看>>
数据类型 java转换
查看>>
"NetworkError: 400 Bad Request - http://172.16.47.117:8088/rhip/**/####t/approval?date=976
查看>>
mybatis 根据 数据库表 自动生成 实体
查看>>
C结构体、C++结构体、C++类的区别
查看>>
进程和线程的概念、区别和联系
查看>>