【问题标题】:Thread.Sleep 'breaks' TaskThread.Sleep“休息”任务
【发布时间】:2011-11-30 07:46:07
【问题描述】:

所以我有以下代码

 Action d = () =>
                {                                                             
                   for (int i = 0; i <= 10; i++)
                   {
                      Thread.Sleep(50);
                      Console.WriteLine("Task: {0} log:{1}",Thread.CurrentThread.ManagedThreadId,i);
                   }
                };
 Task.Factory.StartNew(d);

但是它不输出任何东西。但如果我评论 Thread.Sleep,它会按预期工作。使用不同的睡眠值会根据值获得或多或少的结果。

为什么会这样?

【问题讨论】:

    标签: multithreading c#-4.0 .net-4.0 task thread-sleep


    【解决方案1】:

    我怀疑你的程序在任务有机会运行之前就退出了。

    默认情况下,任务在线程池线程上运行,这些线程是后台线程。这意味着您的程序在退出之前不会等待它们完成。

    尝试在你的主线程上添加这个:

    var task = Task.Factory.StartNew( d );
    task.Wait();
    

    【讨论】:

      【解决方案2】:

      您是在任何地方等待任务完成,还是您的程序在任务完成之前退出?

      Task task = Task.Factory.StartNew(d);
      task.Wait();
      

      【讨论】:

      • 因为有更多细节,我选择了其他答案
      【解决方案3】:

      我刚刚运行了你的代码,它会输出:

      Task: 10 log:0
      Task: 10 log:1
      Task: 10 log:2
      Task: 10 log:3
      Task: 10 log:4
      Task: 10 log:5
      Task: 10 log:6
      Task: 10 log:7
      Task: 10 log:8
      Task: 10 log:9
      Task: 10 log:10
      

      这是基于我运行的代码应用程序的控制台代码:

      using System.Threading;
      using System.Threading.Tasks;
      
      namespace ConsoleApplication1
      {
        class Program
        {
          static void Main(string[] args)
          {
            Action d = () =>
            {
              for (int i = 0; i <= 10; i++)
              {
                Thread.Sleep(50);
                Console.WriteLine("Task: {0} log:{1}", Thread.CurrentThread.ManagedThreadId, i);
              }
            };
            Task.Factory.StartNew(d);
            Console.ReadLine();
          }
        }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-12-18
        • 1970-01-01
        • 2019-01-09
        • 1970-01-01
        • 1970-01-01
        • 2011-10-09
        • 1970-01-01
        相关资源
        最近更新 更多