dotnet Core 异步任务

血红的双手。 提交于 2021-01-24 13:37:44

使用线程池中线程的任务启动方式

线程池提供了一个后台线程的池,独自管理线程,按需增加或减少线程池中的线程数。线程池中的线程用于执行一些动作后仍然返回线程池中。

 

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

namespace TaskSamples
{
  class Program
  {
    static void Main()
    {
      TasksUsingThreadPool();
      Console.ReadLine();
    }

    

    static void TasksUsingThreadPool()
    {
      var tf = new TaskFactory();
      Task t1 = tf.StartNew(TaskMethod, "using a task factory");

      Task t2 = Task.Factory.StartNew(TaskMethod, "factory via a task");

      var t3 = new Task(TaskMethod, "using a task constructor and Start");
      t3.Start();

      Task t4 = Task.Run(() => TaskMethod("using the Run method"));

    }

    static object taskMethodLock = new object();
    static void TaskMethod(object title)
    {
      lock (taskMethodLock)
      {
        Console.WriteLine(title);
        Console.WriteLine("Task id: {0}, thread: {1}",
          Task.CurrentId == null ? "no task" : Task.CurrentId.ToString(),
          Thread.CurrentThread.ManagedThreadId);
        Console.WriteLine("is pooled thread: {0}", Thread.CurrentThread.IsThreadPoolThread);
        Console.WriteLine("is background thread: {0}", Thread.CurrentThread.IsBackground);
        Console.WriteLine();
      }
    }
  }
}

 

  

 

实例化TaskFactory类,将要执行的方法作为参数传递给实例的StartNew方法

var tf = new TaskFactory();
Task t1 = tf.StartNew(TaskMethod, "using a task factory");

使用Task类的静态属性TaskFactory访问TaskFactory,并调用其StartNew方法

Task t2 = Task.Factory.StartNew(TaskMethod, "factory via a task");

使用Task类的构造函数实例化Task对象,并调用其Start方法

var t3 = new Task(TaskMethod, "using a task constructor and Start");
t3.Start();

调用Task类的静态方法Run,参数为一个Action委托

Task t4 = Task.Run(() => TaskMethod("using the Run method"));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!