zoukankan      html  css  js  c++  java
  • Async callback to awaitable Task<> z

    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<PhotoResult> TakePicture()
    {
        var taskCompletionSource = new TaskCompletionSource<PhotoResult>();
        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.

  • 相关阅读:
    Triangle LOVE
    数据传送指令具体解释
    关于C++String字符串的使用
    TCP/IP基础(一)
    java打开目录(含推断操作系统工具类和解压缩工具类)
    hdu-1848 Fibonacci again and again
    opencv2对读书笔记——图像二值化——thresholded函数
    安卓中四种点击事件
    @MappedSuperclass注解的使用说明
    Androidclient採用Http 协议Post方式请求与服务端进行数据交互
  • 原文地址:https://www.cnblogs.com/zeroone/p/3648315.html
Copyright © 2011-2022 走看看