예제 #1
0
        static Task <string> Hello()
        {
            MyStateMachine machine = new MyStateMachine();

            machine.t_builder = AsyncTaskMethodBuilder <string> .Create();

            //TaskCompletionSource

            machine.state = -1;

            var t_builder = machine.t_builder;

            t_builder.Start(ref machine);

            return(machine.t_builder.Task);
        }
예제 #2
0
        public void MoveNext()
        {
            try
            {
                switch (state)
                {
                case -1:
                    Console.WriteLine("hello world");

                    var waiter = Task.Run(() =>
                    {
                        Console.WriteLine("i'm middle");

                        return("i'm ok");
                    }).GetAwaiter();

                    state     = 0;  //设置下一个状态
                    myawaiter = waiter;

                    machine = this;

                    //丢给线程池执行了。。。
                    t_builder.AwaitUnsafeOnCompleted(ref waiter, ref machine);
                    break;

                case 0:

                    var j = myawaiter.GetResult();

                    Console.WriteLine("我是结尾哦:{0}", j);

                    t_builder.SetResult(j);
                    break;
                }
            }
            catch (Exception ex)
            {
                t_builder.SetException(ex);  //设置t_builder的异常
            }
        }