c#-异步编程-异步模式

c#-异步编程-异步模式

using System;
using System.IO;
using System.Net;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp19
{
    class Program
    {
        private const string url = "http://www.baidu.com";
        static async Task Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            //fun();
            //fun2();
            //fun3();
            await fun4();
            Thread.Sleep(8000);
        }
        // 同步调用
        static void fun() {
            using (var client = new WebClient()) {
                string content = client.DownloadString(url);
                Console.WriteLine(content.Substring(0,100));
            }
            Console.WriteLine();
        }
        // 异步模式
        static void fun2() {
            WebRequest r = WebRequest.Create(url);
            IAsyncResult result = r.BeginGetResponse(ReadResponse, null);
            void ReadResponse(IAsyncResult ar) {
                using (WebResponse response = r.EndGetResponse(ar)) {
                    Stream strenm = response.GetResponseStream();
                    var reader = new StreamReader(strenm);
                    string content = reader.ReadToEnd();
                    Console.WriteLine(content.Substring(0, 100));
                    Console.WriteLine();
                }
            }
        }
        // 事件模式
        static void fun3() {
            using (var client = new WebClient()) {
                client.DownloadStringCompleted += (sender, e) =>
                {
                    Console.WriteLine(e.Result.Substring(0, 100));
                };
                client.DownloadStringAsync(new Uri(url));
                Console.WriteLine();
            }
        }
        // 基于任务的异步模式
        static async Task  fun4() {
            using (var client = new WebClient()) {
                string content = await client.DownloadStringTaskAsync(url);
                Console.WriteLine(content.Substring(1, 100));
                Console.WriteLine();
            }
        }
    }
}

在这里插入图片描述
二 同步上下文
使用 async 和 await 关键字之后,一般就会到了当前的线程,通常是ui线程,但是如果执行玩之后,不需要进行uic操作,也可以不进入ui线程,直接在原来的线程,出来。但需要金属设置,因为默认的设置 是会跳转到uix线程的。
continueOnCapturedContext设置为fase就表示不用切换到同步上下文,这样执行的会更快一点。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值