异步编程基础

发布时间 2023-09-24 15:33:10作者: 宁静致远.

使用 async 和 await 进行异步操作的基础知识,其中只会涉及自然异步操作,如 HTTP 请求、数据库指令、Web 服务调用等。

一、需要通过 异步签名实现同步方法时,返回已完成的任务 

如果在继承异步接口或者基类的同时又想同步实现该任务,便可能发生这样的情况。当需要异步接口的简单签名或模拟对象时,或者当需要对异步代码做单元测试时,这项技术特别有用。

 public interface IMyAsyncInterface
    {
        Task<int> GetValueAsync();
        Task DoSomethingAsync();
        Task<T> NotImplementedAsync<T>();
        Task<int> GetValueAsync(CancellationToken token);
        Task<T> DelayResult<T>(T result, TimeSpan delay);
    }

  

 public class MySynchronousImplementation : IMyAsyncInterface
    {
        public async Task<T> DelayResult<T>(T result, TimeSpan delay)
        {//暂停一段时间,当程序需要异步等待一段时间。在进行单元测试或实现重试延迟时,这是一种常见的场景。
            await Task.Delay(delay);
            return result;
        }

        public Task DoSomethingAsync()
        {
            //1.异步签名实现同步方法,并且无返回值
            try
            {
                //DoSomethingSynchronously()
                return Task.CompletedTask;
            }
            catch (Exception ex)
            {//同步实现可能会失败,就应当捕捉异常并通过Task.FromExceptiion 来返回它们。
                return Task.FromException(ex);
            }
        }

        public Task<int> GetValueAsync()
        {
            //2.异步签名实现同步方法,并且有返回值
            return Task.FromResult(13);
        }

        public Task<int> GetValueAsync(CancellationToken token)
        {
            //3.带取消功能的任务 
            if (token.IsCancellationRequested)
                return Task.FromCanceled<int>(token);
            return Task.FromResult(13);
        }

        public Task<T> NotImplementedAsync<T>()
        {
            //4.需要返回异常报错信息
            return Task.FromException<T>(new NotImplementedException());
        }
    }