zoukankan      html  css  js  c++  java
  • 异步编程模型

    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
  • 相关阅读:
    Codeforces Round #687 A. Prison Break
    最小生成树自用笔记(Kruskal算法+prim算法)
    Codeforces Round #686 (Div. 3)(A->D)(模拟,vector,数学)
    Acwing 852. spfa判断负环
    Linux内核分析_课程学习总结报告
    结合中断上下文切换和进程上下文切换分析Linux内核的一般执行过程
    深入理解系统调用
    基于mykernel 2.0编写一个操作系统内核
    何评测一个软件工程师的计算机网络知识水平与网络编程技能水平?——参考试题
    TCP三次握手Linux源码解析
  • 原文地址:https://www.cnblogs.com/liuqifeng/p/9149841.html
Copyright © 2011-2022 走看看