C# 多线程task

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;


namespace 多线程Task
{
    class Program
    {
        static void Main(string[] args)
        {
            Task task = new Task(
                () =>
                {
                    for (int i = 0; i < 10; i++)
                    {
                        Console.WriteLine("Index:{0},ThreadID:{1}",i,Thread.CurrentThread.ManagedThreadId);
                        Thread.Sleep(1000);
                    }
                });
            //在使用能够Task类的Wait方法等待一个任务时或派生类的Result属性获得任务执行结果都有可能阻塞线程,
            //为了解决这个问题可以使用ContinueWith方法,他能在一个任务完成时自动启动一个新的任务来处理执行结果。
            task.ContinueWith(t =>
                {
                    Console.WriteLine("执行完毕!,ThreadID:{0}",  Thread.CurrentThread.ManagedThreadId);
                });
            task.Start();


            Console.WriteLine("主线程执行完毕!ThreadID:{0}",Thread.CurrentThread.ManagedThreadId);
            Console.ReadKey();


        }
    }
}

posted on 2015-07-14 17:09  软件开发学习分享  阅读(264)  评论(0编辑  收藏  举报