码迷,mamicode.com
首页 > Web开发 > 详细

dotnet Core 异步任务

时间:2018-08-24 11:40:35      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:oid   sha   eric   task   readline   and   title   span   对象   

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

 

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"));

dotnet Core 异步任务

标签:oid   sha   eric   task   readline   and   title   span   对象   

原文地址:https://www.cnblogs.com/zhurunlai/p/9528699.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!