• 异步编程模型


    class Program
        {
            static void Main(string[] args)
            {
                var func = new Func<string, string>(i => { return i + "i can fly"; });
    
                var state = func.BeginInvoke("yes,", Callback, func);
    
                Console.Read();
            }
    
            static void Callback(IAsyncResult async)
            {
                var result = async.AsyncState as Func<string, string>;
    
                Console.WriteLine(result.EndInvoke(async));
            }
        }
    View Code
    class Program
        {
            static void Main(string[] args)
            {
                var func = new Func<string, string>(i =>
                {
                    return i + "i can fly";
                });
    
                Task<string>.Factory.FromAsync(func.BeginInvoke, func.EndInvoke, "yes,", null).ContinueWith
                    (i =>
                    {
                        Console.WriteLine(i.Result);
                    });
    
                Console.Read();
            }
        }
    View Code
    static void Main(string[] args)
            {
                var path = "C://1.txt";
    
                FileStream fs = new FileStream(path, FileMode.Open);
    
                FileInfo info = new FileInfo(path);
    
                byte[] b = new byte[info.Length];
    
                var asycState = fs.BeginRead(b, 0, b.Length, (result) =>
                {
                    var file = result.AsyncState as FileStream;
    
                    Console.WriteLine("文件内容:{0}", Encoding.Default.GetString(b));
    
                    file.Close();
    
                }, fs);
    
                Console.WriteLine("我是主线程,我不会被阻塞!");
    
                Console.Read();
            }
    View Code
    static void Main(string[] args)
            {
                var path = "C://1.txt";
    
                FileStream fs = new FileStream(path, FileMode.Open);
    
                FileInfo info = new FileInfo(path);
    
                byte[] b = new byte[info.Length];
    
                Task<int>.Factory.FromAsync(fs.BeginRead, fs.EndRead, b, 0, b.Length, null, TaskCreationOptions.None)
                    .ContinueWith
                    (i =>
                    {
                        Console.WriteLine("文件内容:{0}", Encoding.Default.GetString(b));
                    });
    
                Console.WriteLine("我是主线程,我不会被阻塞!");
    
                Console.Read();
            }
    View Code
    class Program
        {
            static byte[] b;
    
            static void Main()
            {
                string[] array = { "C://1.txt", "C://2.txt", "C://3.txt" };
    
                List<Task<string>> taskList = new List<Task<string>>(3);
    
                foreach (var item in array)
                {
                    taskList.Add(ReadAsyc(item));
                }
    
                Task.Factory.ContinueWhenAll(taskList.ToArray(), i =>
                {
                    string result = string.Empty;
    
                    //获取各个task返回的结果
                    foreach (var item in i)
                    {
                        result += item.Result;
                    }
    
                    //倒序
                    String content = new String(result.OrderByDescending(j => j).ToArray());
    
                    Console.WriteLine("倒序结果:"+content);
                });
    
                Console.WriteLine("我是主线程,我不会被阻塞");
    
                Console.ReadKey();
            }
    
            //异步读取
            static Task<string> ReadAsyc(string path)
            {
                FileInfo info = new FileInfo(path);
    
                byte[] b = new byte[info.Length];
    
                FileStream fs = new FileStream(path, FileMode.Open);
    
                Task<int> task = Task<int>.Factory.FromAsync(fs.BeginRead, fs.EndRead, b, 0, b.Length, null, TaskCreationOptions.None);
    
                //返回当前task的执行结果
                return task.ContinueWith(i =>
                {
                    return i.Result > 0 ? Encoding.Default.GetString(b) : string.Empty;
                }, TaskContinuationOptions.ExecuteSynchronously);
            }
        }
    View Code
    class Program
        {
            static void Main(string[] args)
            {
                WebClient client = new WebClient();
    
                client.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(client_DownloadFileCompleted);
    
                client.DownloadFileAsync(new Uri("http://imgsrc.baidu.com/baike/abpic/item/6a600c338744ebf844a0bc74d9f9d72a6159a7ac.jpg"),
                                       "1.jpg", "图片下完了,你懂的!");
    
                Console.WriteLine("我是主线程,我不会被阻塞!");
                Console.Read();
            }
    
            static void client_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
            {
                Console.WriteLine("
    " + e.UserState);
            }
        }
    View Code
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.IO;
    using System.Threading.Tasks;
    using System.Net;
    using System.ComponentModel;
    
    namespace ConsoleApplication4
    {
        class Program
        {
            static void Main()
            {
                var downloadTask = DownLoadFileInTask(
                        new Uri(@"http://www.7720mm.cn/uploadfile/2010/1120/20101120073035736.jpg")
                        , "C://1.jpg");
    
                downloadTask.ContinueWith(i =>
                {
                    Console.WriteLine("图片:" + i.Result + "下载完毕!");
                });
    
                Console.WriteLine("我是主线程,我不会被阻塞!");
    
                Console.Read();
            }
    
            static Task<string> DownLoadFileInTask(Uri address, string saveFile)
            {
                var wc = new WebClient();
    
                var tcs = new TaskCompletionSource<string>(address);
    
                //处理异步操作的一个委托
                AsyncCompletedEventHandler handler = null;
    
                handler = (sender, e) =>
                {
                    if (e.Error != null)
                    {
                        tcs.TrySetException(e.Error);
                    }
                    else
                    {
                        if (e.Cancelled)
                        {
                            tcs.TrySetCanceled();
                        }
                        else
                        {
                            tcs.TrySetResult(saveFile);
                        }
                    }
    
                    wc.DownloadFileCompleted -= handler;
                };
    
                //我们将下载事件与我们自定义的handler进行了关联
                wc.DownloadFileCompleted += handler;
    
                try
                {
                    wc.DownloadFileAsync(address, saveFile);
                }
                catch (Exception ex)
                {
                    wc.DownloadFileCompleted -= handler;
    
                    tcs.TrySetException(ex);
                }
    
                return tcs.Task;
            }
        }
    }
    View Code
  • 相关阅读:
    剑指OFFER----面试题17- 打印从1到最大的n位数
    剑指OFFER----面试题16. 数值的整数次方
    剑指OFFER----面试题15. 二进制中1的个数
    剑指OFFER----面试题14- II. 剪绳子II
    07 多层if判断
    08 while循环
    06 if 流程控制
    03 身份运算符、逻辑运算符
    04 位运算符、运算符优先级
    02 赋值运算符、成员运算符
  • 原文地址:https://www.cnblogs.com/liuqifeng/p/9149841.html
Copyright © 2020-2023  润新知