C# 5.0 以Task方式實現EAP

調用BackgroundWorker相關的方法

以下代碼參考自《Multithreading in C# 5.0 Cookbook》

using System;
using System.ComponentModel;
using System.Threading;
using System.Threading.Tasks;

namespace EAPDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            var tcs = new TaskCompletionSource<int>();

            Console.WriteLine("main is running on a thread id {0}. is thread pool thread:{1}, priority {2}",
                Thread.CurrentThread.ManagedThreadId,
                Thread.CurrentThread.IsThreadPoolThread,
                Thread.CurrentThread.Priority);

            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);
                }
            };
            //Console.WriteLine("----------- 0 ---------------");
            worker.RunWorkerAsync();

            int result = tcs.Task.Result;

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

            Console.ReadKey();
        }

        static int TaskMethod(string name, int seconds)
        {
            Console.WriteLine("Task {0} is running on a thread id {1}. is thread pool thread:{2}, priority {3}",
                name,
                Thread.CurrentThread.ManagedThreadId,
                Thread.CurrentThread.IsThreadPoolThread,
                Thread.CurrentThread.Priority);
            Thread.Sleep(TimeSpan.FromSeconds(seconds));
            return 42 * seconds;
        }
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章