C#异步执行方法的几种方式

C#异步编程资料

基于任务的异步模式 (TAP) 是基于 System.Threading.Tasks 命名空间中的 System.Threading.Tasks.Task 和 System.Threading.Tasks.Task 类型,这些类型用于表示任意异步操作。 TAP 是用于新开发的建议的异步设计模式。这是在 .NET 中进行异步编程的推荐方法

异步概述
https://docs.microsoft.com/zh-cn/dotnet/standard/async
深入了解异步
https://docs.microsoft.com/zh-cn/dotnet/standard/async-in-depth

C# 9.0 中的新增功能
https://docs.microsoft.com/zh-cn/dotnet/csharp/whats-new/csharp-9

Task 类
https://docs.microsoft.com/zh-cn/dotnet/api/system.threading.tasks.task?view=netcore-3.1

异步编程模式
https://docs.microsoft.com/zh-cn/dotnet/standard/asynchronous-programming-patterns/

方式一(推荐):

Task.Run(Func<Task> function);

方式二:

ThreadPool.QueueUserWorkItem(WaitCallback callBack);
using System.Threading.Tasks;
//
// 摘要:
//     将在线程池上运行的指定工作排队,并返回 function 所返回的任务的代理项。
//
// 参数:
//   function:
//     以异步方式执行的工作量。
//
// 返回结果:
//     表示由 function 返回的任务代理的任务。
//
// 异常:
//   T:System.ArgumentNullException:
//     function 参数是 null。
public static Task Run(Func<Task> function);

using System.Threading;
 //
 // 摘要:
 //     将方法排入队列以便执行。 此方法在有线程池线程变得可用时执行。
 //
 // 参数:
 //   callBack:
 //     一个 System.Threading.WaitCallback,表示要执行的方法。
 //
 // 返回结果:
 //     如果此方法成功排队,则为 true;如果无法将该工作项排队,则引发 System.NotSupportedException。
 //
 // 异常:
 //   T:System.ArgumentNullException:
 //     callBack 为 null。
 //
 //   T:System.NotSupportedException:
 //     承载公共语言运行时 (CLR) 的宿主不支持此操作。
 [SecuritySafeCritical]
 public static bool QueueUserWorkItem(WaitCallback callBack);

调用参考:

static void Main(string[] args)
{
            Console.WriteLine("执行1");
            bool isQue = ThreadPool.QueueUserWorkItem(async a =>
            {
                Console.WriteLine("异步执行2");
                WebClient webClient = new WebClient();
                string url = "http://www.baidu.com";          
                string html = await webClient.DownloadStringTaskAsync(url);
                Console.WriteLine("结果2=" + html.Length);
            });
            Console.WriteLine("isQue="+ isQue);

            Task.Run(async () => {
                Console.WriteLine("异步执行3");
                WebClient webClient = new WebClient();
                string url = "http://www.baidu.com";         
                string html = await webClient.DownloadStringTaskAsync(url);
                Console.WriteLine("结果3="+html.Length);
            });
}

执行结果:
执行1
isQue=True
异步执行2
异步执行3
结果3=14355
结果2=14355

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

王焜棟琦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值