Ejemplo n.º 1
0
        private Task <int> CountCharacters(int id, string address)
        {
            CountCharactersStateMachine stateMachine = new CountCharactersStateMachine();

            stateMachine.builder = AsyncTaskMethodBuilder <int> .Create();

            stateMachine._this   = this;
            stateMachine.id      = id;
            stateMachine.address = address;
            stateMachine.state   = -1;
            stateMachine.builder.Start(ref stateMachine);
            return(stateMachine.builder.Task);
        }
Ejemplo n.º 2
0
            void IAsyncStateMachine.MoveNext()
            {
                int num = state;
                int length;

                try
                {
                    if (num != 0)
                    {
                        Console.WriteLine(string.Format("Thread id is {0}", Thread.CurrentThread.ManagedThreadId));

                        client = new WebClient();
                    }
                    try
                    {
                        TaskAwaiter <string> awaiter;
                        if (num != 0)
                        {
                            Console.WriteLine(string.Format(" 开 始调用 id = {0}:{1} ms", id, Watch.ElapsedMilliseconds));
                            Thread.Sleep(1000);
                            awaiter = client.DownloadStringTaskAsync(address).GetAwaiter();
                            if (!awaiter.IsCompleted)
                            {
                                num = (state = 0);

                                u = awaiter;

                                CountCharactersStateMachine stateMachine = this;

                                builder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine);
                                return;
                            }
                        }
                        else
                        {
                            awaiter = u;

                            u   = default(TaskAwaiter <string>);
                            num = (state = -1);
                        }

                        s = awaiter.GetResult();

                        result = s;

                        s = null;
                        Console.WriteLine(string.Format(" 调 用完成 id = {0}:{1} ms", id, Watch.ElapsedMilliseconds));
                        length = result.Length;
                    }
                    finally
                    {
                        if (num < 0 && client != null)
                        {
                            ((IDisposable)client).Dispose();
                        }
                    }
                }
                catch (Exception exception)
                {
                    state = -2;
                    builder.SetException(exception);
                    return;
                }
                state = -2;
                builder.SetResult(length);
            }