其他分享
首页 > 其他分享> > 第4章 使用任务并行库

第4章 使用任务并行库

作者:互联网

4.2 创建任务

static void Main(string[] args)
{
    var t1 = new Task(()=>TaskMethod("task1"));
    var t2 = new Task(()=>TaskMethod("task2"));
    t2.Start();
    t1.Start();
    Task.Run(()=>TaskMethod("task3"));
    Task.Factory.StartNew(()=>TaskMethod("task4"));
    Task.Factory.StartNew(()=>TaskMethod("task5"),TaskCreationOptions.LongRunning);
    Thread.Sleep(TimeSpan.FromSeconds(1));
    Console.Read();
}
static void TaskMethod(string name)
{
    Console.WriteLine("task {0} is running on a thread id{1}. is thread pool thread:{2}",name,Thread.CurrentThread.ManagedThreadId,Thread.CurrentThread.IsThreadPoolThread);
}

4.3 使用任务执行基本的操作

Main方法
 #region 4.3
Class4_3.TaskMethod("“t0”");
Task<int> task = Class4_3.CreateTask("t1");
task.Start();
int result = task.Result;//获得任务结果值
Console.WriteLine("result is {0}",result);

task = Class4_3.CreateTask("t2");
task.RunSynchronously();// 对当前的 TaskScheduler 同步运行Task。
result = task.Result;
Console.WriteLine("result is {0}", result);

task = Class4_3.CreateTask("t3");
task.Start();
while (!task.IsCompleted)
{
    Console.WriteLine(task.Status);//任务状态
    Thread.Sleep(500);
}
Console.WriteLine(task.Status);
result = task.Result;
Console.WriteLine("result is {0}", result);
 
#endregion  
            
public  class Class4_3
{
    public static Task<int> CreateTask(string name)
    {
        return new Task<int>(()=>TaskMethod(name));
    }

    public static int TaskMethod(string name)
    {
        Console.WriteLine("task {0} is running on a thread id {1} .is thread pool thread:{2}",name,Thread.CurrentThread.ManagedThreadId,Thread.CurrentThread.IsThreadPoolThread);
        Thread.Sleep(1000);
        return 42;
    }
}

工作原理

标签:Task,并行,任务,task,线程,result,使用,TaskMethod
来源: https://www.cnblogs.com/anjun-xy/p/12002431.html