博客
关于我
C# Async和Await异步任务
阅读量:522 次
发布时间:2019-03-08

本文共 3173 字,大约阅读时间需要 10 分钟。

C# 异步方法入门指导

C# 提供了一种强大的异步编程模型,使开发者能够在不阻塞主线程的情况下执行耗时任务。本节将详细介绍如何使用异步方法,并通过代码示例展示其应用场景。

异步方法的基本语法

在 C# 中,方法前加上 async 关键字即可将其变为异步方法。异步方法可以返回以下几种类型:

  • void
  • Task<TResult>(如 Task<bool>, Task<string>

异步方法命名示例

为了让程序中的异步方法更直观,我们常常在方法名称后面加上 Async 进行区分。例如:

  • void ReadFileAsync(string fileName)

这种命名习惯能够让开发者一目了然地知道方法是否是异步执行的。

异步方法的执行流程

在异步方法的实现部分,为了确保耗时任务能够非阻塞地执行,通常会在方法体内使用 await 关键字。await 会暂停当前线程,等待任务完成后再继续执行后续代码。

示例代码实现

public async Task
TestAsync(){ return await Task.Run(() => { Thread.Sleep(100); Thread currentThread = Thread.CurrentThread; Console.WriteLine("这里开始执行一个用时较长的任务.标识【{0}】,优先级【{1}】,是后台线程【{2}】", currentThread.ManagedThreadId, currentThread.Priority, currentThread.IsBackground); for (int i = 0; i < 3000000; i++) { Interlocked.Increment(ref location); } Console.WriteLine("任务执行完毕!结果【{0}】.标识【{1}】,优先级【{2}】,是后台线程【{3}】", location, currentThread.ManagedThreadId, currentThread.Priority, currentThread.IsBackground); return true; });}

异步任务的优雅管理

在实际开发中,为了保证应用程序的性能和响应速度,合理管理异步任务至关重要。Task.WaitAll 方法用于等待多个任务同时完成,这在需要保证所有异步操作完成之前不继续后续操作的场景中非常有用。

测试程序完整代码

以下是完整的测试程序代码示例:

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading;using System.Threading.Tasks;namespace MethodAsyncDemo{    static void Main(string[] args)    {        Console.WriteLine("程序开始执行。。。主线程标识【{0}】,优先级【{1}】,是后台线程【{2}】",             Thread.CurrentThread.ManagedThreadId,             Thread.CurrentThread.Priority,             Thread.CurrentThread.IsBackground);        List
taskCollection = new List
(); for (int i = 0; i < 5; i++) { Task
task = TestAsync(); taskCollection.Add(task); } Console.WriteLine("这里非阻塞执行,如果遇到Wait将阻塞"); Thread.Sleep(120); Console.WriteLine("下面请等待所有线程(任务)执行完毕,阻塞中...请稍候。{0}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")); Task.WaitAll(taskCollection.ToArray()); Console.WriteLine("所有任务都已执行完毕.{0}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")); Console.WriteLine("继续执行其他流程"); Console.ReadLine(); } static int location = 0; ///
/// 异步任务 /// ///
static async Task
TestAsync() { return await Task.Run(() => { Thread.Sleep(100); Thread currentThread = Thread.CurrentThread; Console.WriteLine("这里开始执行一个用时较长的任务.标识【{0}】,优先级【{1}】,是后台线程【{2}】", currentThread.ManagedThreadId, currentThread.Priority, currentThread.IsBackground); for (int i = 0; i < 3000000; i++) { Interlocked.Increment(ref location); } Console.WriteLine("任务执行完毕!结果【{0}】.标识【{1}】,优先级【{2}】,是后台线程【{3}】", location, currentThread.ManagedThreadId, currentThread.Priority, currentThread.IsBackground); return true; }); }}

结论

通过上述指导和示例代码,可以清楚地看出 C# 异步方法的实现方式及其实际应用场景。在实际开发中,合理使用异步方法能够极大地提升程序的性能和用户体验。

转载地址:http://avqnz.baihongyu.com/

你可能感兴趣的文章
NMAP网络扫描工具的安装与使用
查看>>
NMF(非负矩阵分解)
查看>>
NN&DL4.1 Deep L-layer neural network简介
查看>>
NN&DL4.3 Getting your matrix dimensions right
查看>>
NN&DL4.8 What does this have to do with the brain?
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
NO 157 去掉禅道访问地址中的zentao
查看>>
No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
查看>>
No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
查看>>
No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
查看>>
No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
查看>>
No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
查看>>
No module named 'crispy_forms'等使用pycharm开发
查看>>
No module named cv2
查看>>
No module named tensorboard.main在安装tensorboardX的时候遇到的问题
查看>>
No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
查看>>
No new migrations found. Your system is up-to-date.
查看>>
No qualifying bean of type XXX found for dependency XXX.
查看>>
No resource identifier found for attribute 'srcCompat' in package的解决办法
查看>>
no session found for current thread
查看>>