首页 > 编程语言 >.net 4.0环境下支持 async 异步编程

.net 4.0环境下支持 async 异步编程

时间:2022-11-10 10:35:12浏览次数:49  
标签:task 4.0 stateMachine void Task TStateMachine async net public

 

 这时候编译器会报一个错误 :CS1061 “Task”未包含“GetAwaiter”的定义,并且找不到可接受第一个“Task”类型参数的可访问扩展方法“GetAwaiter”(是否缺少 using 指令或程序集引用?) 

扩展代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Security;
using System.Text;
using System.Threading.Tasks;

namespace System.Threading.Tasks
{
    internal static class TaskEx
    {
        public static TaskAwaiter GetAwaiter(this Task task)
        {
            return new TaskAwaiter(task);
        }

        public static TaskAwaiter<T> GetAwaiter<T>(this Task<T> task)
        {
            return new TaskAwaiter<T>(task);
        }
        public static Task Run(Action action)
        {
            return Task.Factory.StartNew(action);
        }
    }
    internal struct TaskAwaiter : INotifyCompletion
    {
        readonly Task task;
        internal TaskAwaiter(Task task)
        {
            this.task = task;
        }

        internal static TaskScheduler TaskScheduler
        {
            get
            {
                if (SynchronizationContext.Current == null)
                    return TaskScheduler.Default;
                else
                    return TaskScheduler.FromCurrentSynchronizationContext();
            }
        }

        public bool IsCompleted
        {
            get { return task.IsCompleted; }
        }

        public void OnCompleted(Action continuation)
        {
            this.task.ContinueWith(
                delegate (Task task) {

                    //Console.WriteLine("状态机回调函数信息:"+Thread.CurrentThread.ManagedThreadId);
                    //Console.WriteLine("\t名称:"+continuation.Method.Name);
                    //Console.WriteLine("\t所属类型:" + continuation.Method.DeclaringType.ToString());
                    continuation();
                }, TaskAwaiter.TaskScheduler);
        }

        public void GetResult()
        {
            try
            {
                task.Wait();
            }
            catch (AggregateException ex)
            {
                throw ex.InnerExceptions[0];
            }
        }
    }

    internal struct TaskAwaiter<T> : INotifyCompletion
    {
        readonly Task<T> task;

        internal TaskAwaiter(Task<T> task)
        {
            this.task = task;
        }

        public bool IsCompleted
        {
            get { return task.IsCompleted; }
        }

        public void OnCompleted(Action continuation)
        {
            this.task.ContinueWith(
                delegate (Task<T> task) {
                    continuation();
                }, TaskAwaiter.TaskScheduler);
        }

        public T GetResult()
        {
            try
            {
                return task.Result;
            }
            catch (AggregateException ex)
            {
                throw ex.InnerExceptions[0];
            }
        }
    }
}

namespace System.Runtime.CompilerServices
{
    internal interface INotifyCompletion
    {
        void OnCompleted(Action continuation);
    }

    internal interface ICriticalNotifyCompletion : INotifyCompletion
    {
        [SecurityCritical]
        void UnsafeOnCompleted(Action continuation);
    }

    internal interface IAsyncStateMachine
    {
        void MoveNext();
        void SetStateMachine(IAsyncStateMachine stateMachine);
    }

    internal struct AsyncVoidMethodBuilder
    {
        public static AsyncVoidMethodBuilder Create()
        {
            return new AsyncVoidMethodBuilder();
        }

        public void SetException(Exception exception)
        {
            throw exception;
        }

        public void SetResult()
        {
        }

        public void SetStateMachine(IAsyncStateMachine stateMachine)
        {
            // Should not get called as we don't implement the optimization that this method is used for.
            throw new NotImplementedException();
        }

        public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine
        {
            stateMachine.MoveNext();
        }

        public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine
        {
            awaiter.OnCompleted(stateMachine.MoveNext);
        }

        public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine
        {
            awaiter.OnCompleted(stateMachine.MoveNext);
        }
    }

    internal struct AsyncTaskMethodBuilder
    {
        TaskCompletionSource<object> tcs;

        public Task Task { get { return tcs.Task; } }

        public static AsyncTaskMethodBuilder Create()
        {
            AsyncTaskMethodBuilder b;
            b.tcs = new TaskCompletionSource<object>();
            return b;
        }

        public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine
        {
            stateMachine.MoveNext();
        }

        public void SetStateMachine(IAsyncStateMachine stateMachine)
        {
            // Should not get called as we don't implement the optimization that this method is used for.
            throw new NotImplementedException();
        }

        public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine
        {
            awaiter.OnCompleted(stateMachine.MoveNext);
        }

        public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine
        {
            awaiter.OnCompleted(stateMachine.MoveNext);
        }

        public void SetResult()
        {
            tcs.SetResult(null);
        }

        public void SetException(Exception exception)
        {
            tcs.SetException(exception);
        }
    }

    internal struct AsyncTaskMethodBuilder<T>
    {
        TaskCompletionSource<T> tcs;

        public Task<T> Task { get { return tcs.Task; } }

        public static AsyncTaskMethodBuilder<T> Create()
        {
            AsyncTaskMethodBuilder<T> b;
            b.tcs = new TaskCompletionSource<T>();
            return b;
        }

        public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine
        {
            stateMachine.MoveNext();
        }

        public void SetStateMachine(IAsyncStateMachine stateMachine)
        {
            // Should not get called as we don't implement the optimization that this method is used for.
            throw new NotImplementedException();
        }

        public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine
        {
            awaiter.OnCompleted(stateMachine.MoveNext);
        }

        public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine
        {
            AwaitOnCompleted(ref awaiter, ref stateMachine);
        }

        public void SetResult(T result)
        {
            tcs.SetResult(result);
        }

        public void SetException(Exception exception)
        {
            tcs.SetException(exception);
        }
    }
}
View Code

 

标签:task,4.0,stateMachine,void,Task,TStateMachine,async,net,public
From: https://www.cnblogs.com/cyj0923/p/16876253.html

相关文章

  • asyncio
    IO密集型应用IO密集型应用CPU等待IO时间远大于CPU自身运行时间,太浪费;常见的IO密集型业务包括:浏览器交互、磁盘请求、网络爬虫、数据库请求等  Python世界......
  • ASP.NET Core教程-Configuration(配置)-JWT
    更新记录转载请注明出处:2022年11月10日发布。2022年11月8日从笔记迁移到博客。JWT基础JWT是什么(WhatisJWT)JSONWebToken(JWT)是目前最流行的跨域身份验证解决......
  • .NET 7 AOT 的使用以及 .NET 与 Go 互相调用
    目录背景C#部分环境要求创建一个控制台项目体验AOT编译C#调用库函数减少体积C#导出函数C#调用C#生成的AOTGolang部分安装GCCGolang导出函数.NETC#和Golang......
  • 激光雷达-Resnet-推荐系统分析
    激光雷达-Resnet-推荐系统分析参考文献链接https://mp.weixin.qq.com/s/LoCJnKa8Ty2ytCbXS2jPowhttps://www.zhihu.com/question/64494691/answer/786270699?utm_campaig......
  • CSharp: Prototype Pattern in donet 6
     ///<summary>///原型模式PrototypePattern///</summary>publicinterfaceIColorPrototype{///<summary>///......
  • mac 开发C#,.net 工具推荐
    注意:Mac开发.net,一定要是.netcore以上的版本!!!!!!!!如果是不跨平台的.net只能用windows系统!!top1:第一名我还是觉得是IntelliJ家的Rider,虽然是收费的但是用起来真的丝......
  • CSharp: Singleton Pattern in donet 6
     ///<summary>///单例模式单件模式、SingletonPattern///</summary>publicabstractclassBaseGreeter{publicvirtualvoid......
  • .Net Core依赖注入
     依赖注入来自于ServiceCollection这个类ServiceCollectionserver=newServiceCollection();server.AddTransient()//瞬时,每一次获取都是一个新的对象server.AddSin......
  • Netty(一)深入理解网络通信和TCP/IP协议
    一、前言为什么要学Netty?实话说工作中真正用到netty开发的场景可能不算特别多,但是为啥要学这玩意呢?有一说一,变强的路上技能可以用不到,但是不能没有~Java生态圈......
  • HDU 3695 Computer Virus on Planet Pandora
    ProblemDescription    AliensonplanetPandoraalsowritecomputerprogramslikeus.Theirprogramsonlyconsistofcapitalletters(‘A’to‘Z’......