2024-01-15

Run(Action)

将在线程池上运行的指定工作排队,并返回代表该工作的 Task 对象。

C#复制

public static System.Threading.Tasks.Task Run (Action action);
using System;
using System.Threading;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      ShowThreadInfo("Application");

      var t = Task.Run(() => ShowThreadInfo("Task") );
      t.Wait();
   }

   static void ShowThreadInfo(String s)
   {
      Console.WriteLine("{0} thread ID: {1}",
                        s, Thread.CurrentThread.ManagedThreadId);
   }
}
// The example displays the following output:
//       Application thread ID: 1
//       Task thread ID: 3

以异步方式执行的工作。

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

public class Example
{
   public static void Main()
   {
      Console.WriteLine("Application thread ID: {0}",
                        Thread.CurrentThread.ManagedThreadId);
      var t = Task.Run(() => {  Console.WriteLine("Task thread ID: {0}",
                                   Thread.CurrentThread.ManagedThreadId);
                             } );
      t.Wait();
   }
}
// The example displays the following output:
//       Application thread ID: 1
//       Task thread ID: 3

2024-01-15

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 一、 async 同步和异步是两种不同的执行模式,在执行方法和线程利用上会有所不同 同步是按照程序流由上到下的方式...
    三千阑干阅读 286评论 0 0
  • 0、获取输入参数的实际名称 使用nameof 1、枚举的转换 2、C#判断对象类型 3、用反射动态绑定控件事件 容...
    宅玖蔡阅读 1,043评论 0 0
  • .NET .NET 平台是一个开发框架,支持多种编程语言,用于构建各种类型的应用程序,包括桌面应用、Web 应用、...
    三千阑干阅读 183评论 0 0
  • 生活系列记录(八十二) ...
    奉法如天阅读 52评论 0 1
  • 男人的凄惨:婚后不如单身 那天,跟一个哥们约定聚餐,几杯酒下肚,他逐渐打开了话匣子,似乎自打三年前结婚后,他的状态...
    森林走心篇章阅读 69评论 0 0