• 异步编程模型


    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
  • 相关阅读:
    sb#run():
    aop编程,自定义注解参数和方法范围
    vue 工程化
    mybatis SqlSession
    java传时间
    树的同构
    串的模式匹配
    堆栈模拟队列
    银行业务队列简单模拟
    一元多项式的乘法与加法运算
  • 原文地址:https://www.cnblogs.com/liuqifeng/p/9149841.html
Copyright © 2020-2023  润新知