博客
关于我
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/

你可能感兴趣的文章
Python--Redis实战:第四章:数据安全与性能保障:第4节:复制
查看>>
python--基本代码规范
查看>>
Python--抽象类接口类
查看>>
PYTHON--欧拉习题二
查看>>
python--高级应用总结
查看>>
python-520表白代码,我看谁说程序员不懂浪漫,送你几套表白代码,一步到位
查看>>
Python-Asyncio TypeError:无法在‘;等待‘;表达式中使用对象DICT
查看>>
Python-AttributeError:‘;dict&39;对象没有属性‘;序列‘;
查看>>
Python-ldap:是否可以在不显式写入密码的情况下进行绑定?
查看>>
python出现 unknown encoding: idna 的处理方法
查看>>
Python出现 RuntimeError: dictionary changed size during iteration 的解决方法
查看>>
Python-numpy(2)数组的操作
查看>>
Python-Numpy的tile函数用法
查看>>
python-open函数
查看>>
Python-Pandas-将特定函数应用于给定级别-多索引数据框架
查看>>
python-queue队列通信
查看>>
python-ros No module named PyKDL
查看>>
python-social-auth 是否需要会话
查看>>
Python再获年度编程语言,微软或成最大赢家
查看>>
python-week5
查看>>