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

it2024-07-29  37

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

最新回复(0)