参考

Task返回值问题

1、Task方法如果加了async关键字,那么就是异步返回方法,如果是异步返回方法,需要返回一个值时,直接return value

2、 Task方法如果没有加async关键字,需要返回一个值时,使用Task.FromResult方法,Task.FromResult(value)。

尽量不使用.Result获取值这会将异步请求转同步,这些操作都是会导致死锁的。

 

 

 

using Bogus;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;

namespace ConsoleApp6
{
    class Program
    {
        static void Main(string[] args)
        {
            MyDownLoadString ds = new MyDownLoadString();
            ds.DoRun();
            Console.WriteLine("");          
            Console.ReadKey();
        }                     
    }

    class MyDownLoadString
    {    
        

        public void DoRun()
        {
            Task<int> t1 = CountCharactersAsync("第一组", 5000);
            Task<int> t2 = CountCharactersAsync("第二组", 50);
            Console.WriteLine("");
            //如果屏蔽掉下面返回值的输出,那么控制台上会先打印 一,因为要获取异步的返回值导致输出“一”必须等待异步全部执行完才能执行
            var d = t1.Result + t2.Result;
            Console.WriteLine($"d的值:{d}");
            //Console.WriteLine($"第一组返回值:{t1.Result}");
            //Console.WriteLine($"第二组返回值:{t2.Result}");
        }

        private async Task<int> CountCharactersAsync(string str,int a)
        {
          
           var ss =  await  Task.Run(() =>
            {
                Thread.Sleep(a);
                int r = 0;
                for (int i = 0; i < a; i++)
                {
                    r += i;
                }            
                Console.WriteLine($"{str}的值:{r}");
                return r;
            });           
            Console.WriteLine($"三:{str}");
            return ss;
        }      
    }
}

 

async和await

1、不是说 async Task<int>放在这个修饰的执行的操作或方法是异步的,而是在这个修饰方法里面有await修饰的才是异步的

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;

namespace ConsoleApp5
{
    class Program
    {
        static void Main(string[] args)
        {
            MyDownLoadString ds = new MyDownLoadString();
            ds.DoRun();
            Console.ReadKey();
        }
    }
    class MyDownLoadString
    {
        Stopwatch sw = new Stopwatch();
        public void DoRun()
        {
            const int LargeNumber = 6000000;
            sw.Start();
            // Task<int> 保存结果对象,后面t1.Result则是获取结果
            Task<int> t1 = CountCharactersAsync(1, "http://www.microsoft.com");
            Task<int> t2 = CountCharactersAsync(2, "http://www.illustratedcsharp.com");

            //无需等待CountCharactersAsync执行完成
            CountToALargeNumber(1, LargeNumber);
            CountToALargeNumber(2, LargeNumber);
            CountToALargeNumber(3, LargeNumber);
            CountToALargeNumber(4, LargeNumber);

            //t1.Result获取结果
            Console.WriteLine("Chars in Call1:{0}", t1.Result);
            Console.WriteLine("Chars in Call1:{0}", t2.Result);
        }

        private async Task<int> CountCharactersAsync(int id, string uriString)
        {
            WebClient wc = new WebClient();
            Console.WriteLine("Call {0} 下载开始: {1:N0}ms ", id, sw.Elapsed.TotalMilliseconds);
            string result = await wc.DownloadStringTaskAsync(new Uri(uriString));
           // Trace.TraceInformation("Taceing Async Call {0} @time:{1:N0}ms", id, sw.Elapsed.TotalMilliseconds);
            Console.WriteLine("Call {0} 下载结束: {1:N0}ms", id, sw.Elapsed.TotalMilliseconds);
            return result.Length;
        }

        private void CountToALargeNumber(int id, int value)
        {
            for (long i = 0; i < value; i++) ;
            Console.WriteLine("End CountToALargeNumber {0}: {1:N0}ms", id, sw.Elapsed.TotalMilliseconds);
        }
    }
    }

2、Task.WhenAll、Task.WhenAny、Task.WaitAll、Task.WaitAny

参考

参考

using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp3
{
    class Program
    {
        private static UdpClient udpcSend;
        static void Main(string[] args)
        {

            MyDownLoadString ds = new MyDownLoadString();
            ds.DoRun();
            Console.ReadKey();
        }       
    }

    class MyDownLoadString 
    {
        public void DoRun() 
        {
            Console.WriteLine("DoRun开始!!!!!!");
            Task t1 = CountCharactersAsync();
            Console.WriteLine("DoRun结束!!!!!!");
        }

        private async Task CountCharactersAsync()
        {

            List<Task> tasks = new List<Task>();
            tasks.Add(Task.Run(async () => {
                Thread.Sleep(10000);
                Console.WriteLine("比对1");
            }));
            tasks.Add(Task.Run(async () => {
                Thread.Sleep(10);
                Console.WriteLine("比对2");
            }));
            tasks.Add(Task.Run(async () => {              
                Console.WriteLine("比对3");
            }));
            tasks.Add(Task.Run(async () => {
                Thread.Sleep(1000);
                Console.WriteLine("比对4");
            }));
            //await Task.WhenAll(tasks);
            //await Task.WhenAny(tasks);
            // Task.WaitAll(tasks.ToArray());
            //Task.WaitAny(tasks.ToArray());//只要一个执行了就往下
            Console.WriteLine("等待结束!!");
        }
    }
}

 

posted on 2020-05-26 11:41  红磨坊后的白桦树  阅读(326)  评论(0编辑  收藏  举报