示例#1
0
        private static void Main(string[] args)
        {
            int threadId;
            AsynchronousTask             d = Test;
            IncompatibleAsynchronousTask e = Test;

            Console.WriteLine("Option 1");
            Task <string> task = Task <string> .Factory.FromAsync(
                d.BeginInvoke("AsyncTaskThread", Callback, "a delegate asynchronous call"), d.EndInvoke);

            task.ContinueWith(t => Console.WriteLine("Callback_1 is finished, now running a continuation! Result: {0}",
                                                     t.Result));

            while (!task.IsCompleted)
            {
                Console.WriteLine("任务状态11:" + task.Status);
                Thread.Sleep(TimeSpan.FromSeconds(0.5));
            }
            Console.WriteLine("任务状态12:" + task.Status);
            Thread.Sleep(TimeSpan.FromSeconds(1));

            Console.WriteLine("----------------------------------------------");
            Console.WriteLine();
            Console.WriteLine("Option 2");

            task = Task <string> .Factory.FromAsync(
                d.BeginInvoke, d.EndInvoke, "AsyncTaskThread", "a delegate asynchronous call");

            task.ContinueWith(t => Console.WriteLine("Task_2 is completed, now running a continuation! Result: {0}",
                                                     t.Result));
            while (!task.IsCompleted)
            {
                Console.WriteLine("任务状态21:" + task.Status);
                Thread.Sleep(TimeSpan.FromSeconds(0.5));
            }
            Console.WriteLine("任务状态22:" + task.Status);
            Thread.Sleep(TimeSpan.FromSeconds(1));

            Console.WriteLine("----------------------------------------------");
            Console.WriteLine();
            Console.WriteLine("Option 3");

            IAsyncResult ar = e.BeginInvoke(out threadId, Callback, "a delegate asynchronous call");

            task = Task <string> .Factory.FromAsync(ar, _ => e.EndInvoke(out threadId, ar));

            task.ContinueWith(t =>
                              Console.WriteLine("Task_3 is completed, now running a continuation! Result: {0}, ThreadId: {1}",
                                                t.Result, threadId));

            while (!task.IsCompleted)
            {
                Console.WriteLine("任务状态31:" + task.Status);
                Thread.Sleep(TimeSpan.FromSeconds(0.5));
            }
            Console.WriteLine("任务状态32:" + task.Status);

            Thread.Sleep(TimeSpan.FromSeconds(1));
            Console.ReadKey();
        }
        public void AsyncTaskReturnsBoolTest()
        {
            {
                var sut = new AsynchronousTask();


                AsyncContext.Run(async() =>
                {
                    var result = await sut.AsyncTaskMethodReturnsBool();

                    result.Should().BeTrue();
                });
            }
        }
        public void AsyncTaskTest()
        {
            {
                var sut = new AsynchronousTask();


                AsyncContext.Run(async() =>
                {
                    await sut.AsyncTaskMethod();

                    sut.value.Should().Be("stringValue");
                });
            }
        }
示例#4
0
        public static void Run()
        {
            int threadId = 0;
            AsynchronousTask            d = Test;
            IncompatibleAsyncronousTask e = Test;
            // Option1
            Task <string> task = Task <string> .Factory.FromAsync(d.BeginInvoke("AsyncTaskThread", Callback, "a delegate asynchronous call"), d.EndInvoke);

            task.ContinueWith(t => Console.WriteLine("callback is finished,now running a continuation!result:{0}", t.Result));

            while (!task.IsCompleted)
            {
                Console.WriteLine(task.Status);
                Thread.Sleep(TimeSpan.FromSeconds(0.5));
            }
            Console.WriteLine(task.Status);
            Console.WriteLine();

            // Option2
            task = Task <string> .Factory.FromAsync(d.BeginInvoke, d.EndInvoke, "AsyncTaskThread", "a delegate asynchronous call");

            task.ContinueWith(t => Console.WriteLine("callback is finished,now running a continuation!result:{0}", t.Result));

            while (!task.IsCompleted)
            {
                Console.WriteLine(task.Status);
                Thread.Sleep(TimeSpan.FromSeconds(0.5));
            }
            Console.WriteLine(task.Status);
            Console.WriteLine();

            // Option3
            IAsyncResult ar = e.BeginInvoke(out threadId, Callback, "a delegate asynchronous call");

            ar   = e.BeginInvoke(out threadId, Callback, "a delegate asynchronous call");
            task = Task <string> .Factory.FromAsync(ar, _ => e.EndInvoke(out threadId, ar));

            task.ContinueWith(t => Console.WriteLine("callback is finished,now running a continuation!result:{0}", t.Result));

            while (!task.IsCompleted)
            {
                Console.WriteLine(task.Status);
                Thread.Sleep(TimeSpan.FromSeconds(0.5));
            }
            Console.WriteLine(task.Status);
            Console.WriteLine();

            Thread.Sleep(TimeSpan.FromSeconds(1));
        }
        public void ApmToTap()
        {
            new Thread(() =>
            {
                int threadId;
                AsynchronousTask d             = Test;
                IncompatibleAsynchronousTask e = Test;
                WriteLine("Option 1");
                Task <string> task = Task <string> .Factory.FromAsync(d.BeginInvoke("AsyncTaskThread", Callback, "a delegate asynchronous call"), d.EndInvoke);
                task.ContinueWith(t => WriteLine($"Callback is finished now running a continuation! Result: {t.Result}"));
                while (!task.IsCompleted)
                {
                    WriteLine(task.Status);
                    Thread.Sleep(TimeSpan.FromSeconds(0.5));
                }
                WriteLine(task.Status);
                Thread.Sleep(TimeSpan.FromSeconds(1));
                WriteLine("-------------------");
                WriteLine();
                WriteLine("Option 2");
                task = Task <string> .Factory.FromAsync(d.BeginInvoke, d.EndInvoke, "AsyncTaskThread", "a delegate asynchronout call");
                task.ContinueWith(t => WriteLine($"Task is Completed, now running a continuation! Result: {t.Result}"));
                while (!task.IsCompleted)
                {
                    WriteLine(task.Status);
                    Thread.Sleep(TimeSpan.FromSeconds(0.5));
                }

                WriteLine(task.Status);
                Thread.Sleep(TimeSpan.FromSeconds(1));

                WriteLine("------------------------");
                WriteLine();
                WriteLine("Option 3");

                IAsyncResult ar = e.BeginInvoke(out threadId, Callback, "a delegate asynchronous call");
                task            = Task <string> .Factory.FromAsync(ar, _ => e.EndInvoke(out threadId, ar));

                task.ContinueWith(t => WriteLine($"Task is completed, now running a continuation! Result: {t.Result}, Thread Id: {threadId}"));

                while (!task.IsCompleted)
                {
                    WriteLine(task.Status);
                    Thread.Sleep(TimeSpan.FromSeconds(0.5));
                }
                WriteLine(task.Status);
                Thread.Sleep(TimeSpan.FromSeconds(1));
            }).Start();
        }
示例#6
0
        static void StartChapter4()
        {
            int threadId;
            AsynchronousTask             d = Test;
            IncompatibleAsynchronousTask e = Test;

            Console.WriteLine("Option 1");
            Task <string> task = Task <string> .Factory.FromAsync(d.BeginInvoke("AsyncTaskThread", CallBack, "a delegate asynchronous call"), d.EndInvoke);

            task.ContinueWith(t => Console.WriteLine("Callback is finished,now running acontinuation! Result:{0}", t.Result));
            while (!task.IsCompleted)
            {
                Console.WriteLine(task.Status);
                Thread.Sleep(TimeSpan.FromSeconds(0.5));
            }
            Console.WriteLine(task.Status);
            Thread.Sleep(TimeSpan.FromSeconds(1));
            Console.WriteLine("----------------------------------");
            Console.WriteLine();
            Console.WriteLine("Option 2");

            task = Task <string> .Factory.FromAsync(d.BeginInvoke, d.EndInvoke, "AsyncTaskThread", "a delegate asynchrounous call");

            while (!task.IsCompleted)
            {
                Console.WriteLine(task.Status);
                Thread.Sleep(TimeSpan.FromSeconds(0.5));
            }
            Console.WriteLine(task.Status);
            Thread.Sleep(TimeSpan.FromSeconds(1));

            Console.WriteLine("-----------------------------------");
            Console.WriteLine();
            Console.WriteLine("Option 3");

            IAsyncResult ar = e.BeginInvoke(out threadId, CallBack, "a delegate asynchronous call");

            task = Task <string> .Factory.FromAsync(ar, _ => e.EndInvoke(out threadId, ar));

            task.ContinueWith(t => Console.WriteLine("Task is completed,now running a continuation:Result {0},Threadid:{1}", t.Result, threadId));
            while (!task.IsCompleted)
            {
                Console.WriteLine(task.Status);
                Thread.Sleep(TimeSpan.FromSeconds(0.5));
            }
            Console.WriteLine(task.Status);
            Thread.Sleep(TimeSpan.FromSeconds(1));
        }
示例#7
0
        //执行的流程是 先执行Test--->task.ContinueWith
        static void Main(string[] args)
        {
            AsynchronousTask d    = Test;
            Task <string>    task = Task <string> .Factory.FromAsync(
                d.BeginInvoke, d.EndInvoke, "AsyncTaskThread", "a delegate asynchronous call");

            task.ContinueWith(t => Console.WriteLine("Task is completed, now running a continuation! Result: {0}",
                                                     t.Result));
            while (!task.IsCompleted)
            {
                Console.WriteLine(task.Status);
                Thread.Sleep(TimeSpan.FromSeconds(0.5));
            }
            Console.WriteLine(task.Status);
            Console.ReadKey();
        }
示例#8
0
        /// <summary>
        /// APM模式转换Task
        /// </summary>
        public static void APMTest()
        {
            int ThreadId;
            AsynchronousTask            d = Test;
            IncompatileAsynchronousTask e = Test;

            Console.WriteLine("Option 1");
            Task <string> task = Task <string> .Factory.FromAsync(d.BeginInvoke("AsyncTaskThread", Callback, "a delegate asynchronous call"), d.EndInvoke);

            task.ContinueWith(t => { Console.WriteLine($"Callback is finished ,now running a continuation resul:{t.Result}"); });

            while (!task.IsCompleted)
            {
                Console.WriteLine(task.Status);
                Thread.Sleep(TimeSpan.FromSeconds(0.5));
            }
            Console.WriteLine(task.Status);
            Thread.Sleep(TimeSpan.FromSeconds(1));
        }
示例#9
0
        static void Main(string[] args)
        {
            int threadId;
            AsynchronousTask             compatiable  = Test;
            IncompatibleAsynchronousTask incompatible = Test;

            Console.WriteLine("Option 1");
            //The key point for converting APM to TPL is a Task<T>.Factory.FromAsync method, where T
            //is the asychronous operation result.
            Task <string> task =
                Task <string> .Factory.FromAsync(
                    compatiable.BeginInvoke("AsyncTaskThread", Callback, "a delegateasynchronous call"),
                    compatiable.EndInvoke);

            task.ContinueWith(
                t => Console.WriteLine("Callback is finished, now running a continuation! Result:{0}", t.Result));

            while (!task.IsCompleted)
            {
                Console.WriteLine(task.Status);
                Thread.Sleep(TimeSpan.FromSeconds(0.5));
            }
            Console.WriteLine(task.Status);
            Thread.Sleep(TimeSpan.FromSeconds(1));

            Console.WriteLine("--------------------------------------------");
            Console.WriteLine();
            Console.WriteLine("Option 2");

            //The overload of FromAsync method doesn't allow specifying a callback that will be executed after
            //the asynchronous delegate call completes. We are able to replace this with continuation, but if
            //the callback is important, we can use the first example.
            task = Task <string> .Factory.FromAsync(compatiable.BeginInvoke, compatiable.EndInvoke, "AsyncTaskThread",
                                                    "adelegateasynchronous call");

            task.ContinueWith(
                t => Console.WriteLine("Task is completed, now running a continuation! Result:{0}", t.Result));
            while (!task.IsCompleted)
            {
                Console.WriteLine(task.Status);
                Thread.Sleep(TimeSpan.FromSeconds(0.5));
            }
            Console.WriteLine(task.Status);
            Thread.Sleep(TimeSpan.FromSeconds(1));

            Console.WriteLine("--------------------------------------------");
            Console.WriteLine();
            Console.WriteLine("Option 3");

            //EndMethod of the IncompatibleAsynchronousTask delegate uses the out parameter, and is
            //not compatible with any FromAsync method overload.
            IAsyncResult ar = incompatible.BeginInvoke(out threadId, Callback, "adelegate asynchronous call");

            task = Task <string> .Factory.FromAsync(ar, _ => incompatible.EndInvoke(out threadId, ar));

            task.ContinueWith(
                t =>
                Console.WriteLine("Task is completed, now running a continuation! Result:{0}, ThreadId:{1}",
                                  t.Result, threadId));
            while (!task.IsCompleted)
            {
                Console.WriteLine(task.Status);
                Thread.Sleep(TimeSpan.FromSeconds(0.5));
            }

            Console.WriteLine(task.Status);
            Thread.Sleep(TimeSpan.FromSeconds(1));
            Console.WriteLine("---------------------------------------");
            Console.WriteLine();
            //To see what is going on with the underlying task, we are printing task.Status while waiting
            //for the asynchronous operation's result. We can see that the output is WaitingForActivation,
            //which means that the task was not actually started yet by the TPL infrastructure.
            /***********Converting from EAP Pattern*********************************/
            var tcs    = new TaskCompletionSource <int>();
            var worker = new BackgroundWorker();

            worker.DoWork += (sender, eventArgs) =>
            {
                eventArgs.Result = TaskMethod("Background worker", 5);
            };
            worker.RunWorkerCompleted += (sender, eventArgs) =>
            {
                if (eventArgs.Error != null)
                {
                    tcs.SetException(eventArgs.Error);
                }
                else if (eventArgs.Cancelled)
                {
                    tcs.SetCanceled();
                }
                else
                {
                    tcs.SetResult((int)eventArgs.Result);
                }
            };
            worker.RunWorkerAsync();
            int result = tcs.Task.Result;

            Console.WriteLine("Result is:{0}", result);

            Console.Read();
        }
示例#10
0
        /// <summary>
        /// 将APM模式转换为任务
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            int threadId;
            AsynchronousTask             d = Test;
            IncompatibleAsynchronousTask e = Test;

            // 将APM转换为TPL的关键是Task<T>.Factory.FromAsync方法
            // 其中T为异步操作结果的类型
            // 该方法有多个重载。

            Console.WriteLine("Option 1");
            // 这种方法可以指定回调函数
            Task <string> task = Task <string> .Factory.FromAsync(
                d.BeginInvoke(
                    "AsyncTaskThread",
                    Callback,
                    "a delegate asynchronous call"),
                d.EndInvoke);

            task.ContinueWith(t => Console.WriteLine($"Callback is finished, now running a continuation! Result: {t.Result}"));

            while (!task.IsCompleted)
            {
                Console.WriteLine(task.Status);
                Thread.Sleep(TimeSpan.FromSeconds(0.5));
            }
            Console.WriteLine(task.Status);
            Thread.Sleep(TimeSpan.FromSeconds(1));

            Console.WriteLine("------------------------------------");
            Console.WriteLine();
            Console.WriteLine("Option 2");

            // 这种方法不能直接指定回调函数
            // 如果需要,可以使用Task.ContinueWith方法执行回调函数。
            task = Task <string> .Factory.FromAsync(
                d.BeginInvoke,
                d.EndInvoke,
                "AsyncTaskThread",
                "a delegate asynchronous call");

            task.ContinueWith(t => Console.WriteLine($"Task is completed, now running a continuation! Result: {t.Result}"));

            while (!task.IsCompleted)
            {
                Console.WriteLine(task.Status);
                Thread.Sleep(TimeSpan.FromSeconds(0.5));
            }
            Console.WriteLine(task.Status);
            Thread.Sleep(TimeSpan.FromSeconds(1));

            Console.WriteLine("------------------------------------");
            Console.WriteLine();
            Console.WriteLine("Option 3");

            // 这里的异步方法带有out参数,导致EndInvoke的签名和FromAsync的签名不一致
            // 这里展示了一个小技巧,使用lambda表达式封装了EndInvoke方法
            IAsyncResult ar = e.BeginInvoke(out threadId, Callback, "a delegate asynchronous call");

            task = Task <string> .Factory.FromAsync(ar, _ => e.EndInvoke(out threadId, ar));

            task.ContinueWith(t => Console.WriteLine($"Task is completed, now running a continuation! Result: {t.Result}, ThreadId: {threadId}"));

            while (!task.IsCompleted)
            {
                Console.WriteLine(task.Status);
                Thread.Sleep(TimeSpan.FromSeconds(0.5));
            }
            Console.WriteLine(task.Status);
            Thread.Sleep(TimeSpan.FromSeconds(1));

            Console.ReadLine();
        }