任务忽略Thread.Sleep [英] Task is ignoring Thread.Sleep

查看:224
本文介绍了任务忽略Thread.Sleep的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图抓住TPL。



只是为了好玩,我试着创建一些任务随机睡眠,看看它是如何处理的。我是针对一个火和忘记模式。

  static void Main(string [] args)
{
Console.WriteLine(演示成功的事务);

Random d = new Random();
for(int i = 0; i <10; i ++)
{
var sleep = d.Next(100,2000);


Action< int> succes =(int x)=>
{
Thread.Sleep(x);
Console.WriteLine(sleep = {2},Task = {0},Thread = {1}:Begin successful transaction,
Task.CurrentId,Thread.CurrentThread.ManagedThreadId,x);
};

任务t1 = Task.Factory.StartNew(()=> succes(sleep));
}
Console.ReadLine();
}

但我不明白为什么它输出所有行到控制台忽略睡眠(随机)



有人可以向我解释吗?

解决方案

重要:



TPL默认TaskScheduler不保证每个任务的线程 - 一个线程可用于处理多个任务。


$ b $



您可以使用 TaskCreationOptions.LongRunning

来构建任务。 / em>提示这样TaskScheduler将为任务分配一个专用的线程,它将安全地阻止它。


trying to grasp the TPL.

Just for fun I tried to create some Tasks with a random sleep to see how it was processed. I was targeting a fire and forget pattern..

static void Main(string[] args)
    {
        Console.WriteLine("Demonstrating a successful transaction");

        Random d = new Random();
        for (int i = 0; i < 10; i++)
        {
            var sleep = d.Next(100, 2000);


            Action<int> succes = (int x) =>
            {
                Thread.Sleep(x);
                Console.WriteLine("sleep={2}, Task={0}, Thread={1}: Begin successful transaction",
                   Task.CurrentId, Thread.CurrentThread.ManagedThreadId, x);
            };

            Task t1 = Task.Factory.StartNew(() => succes(sleep));
        }
        Console.ReadLine();
    }

But I don't understand why it outputs all lines to the Console ignoring the Sleep(random)

Can someone explain that to me?

解决方案

Important:

The TPL default TaskScheduler does not guarantee Thread per Task - one thread can be used for processing several tasks.

Calling Thread.Sleep might impact other tasks performance.

You can construct your task with the TaskCreationOptions.LongRunning hint this way the TaskScheduler will assign a dedicated thread for the task and it will be safe to block on it.

这篇关于任务忽略Thread.Sleep的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆