等待 Task.Delay() 花费太多时间

tad*_*tad 0 c# multithreading task delay async-await

在 C# 中,我有一个例子:

public async static Task TaskTest(int i)
{
    await Task.Delay(1);
    Console.WriteLine($"{i}. {DateTime.Now.ToString("HH:mm:ss fff")} " +
        $"ThreadId:{Thread.CurrentThread.ManagedThreadId} Start");

    int count = 1;
    while (true)
    {
        DoSomeThing(count);

        var stopWatch = new Stopwatch();
        stopWatch.Start();

        await Task.Delay(100);

        stopWatch.Stop();
        if (stopWatch.Elapsed.TotalMilliseconds > 200)
            Console.ForegroundColor = ConsoleColor.Red;

        Console.WriteLine($"Id:{count} Time:{DateTime.Now.ToString("HH:mm:ss fff")} " +
         $"ThreadID:{Thread.CurrentThread.ManagedThreadId} Time Delay:{stopWatch.Elapsed.TotalMilliseconds }");

        Console.ForegroundColor = ConsoleColor.White;
        count++;
    }
}

public async static Task DoSomeThing(int index)
{
    await Task.Delay(1);
    Task.Delay(1000).Wait();
}

private static void Main(string[] args)
{
    int i = 1;
    while (i < 2)
    {
        TaskTest(i);
        Task.Delay(1).Wait();
        i++;
    }
    Console.ReadKey();
}
Run Code Online (Sandbox Code Playgroud)

这是我的 结果

Id:8 时间:23:03:59 972 ThreadID:12 时间延迟:582.6348

Id:22 时间:23:04:01 974 ThreadID:14 时间延迟:552.7234000000001

Id:42 时间:23:04:04 967 ThreadID:8 时间延迟:907.3214

不知道为什么Task有时会延迟200多毫秒。

更新: 感谢所有回答。我更新我的代码以使用 Thread 和 Thread.Sleep() 和 Task.Run()。我将永远运行的线程数增加到 500。我在 30 分钟内进行了测试,500 个线程的睡眠时间从不超过 200 毫秒。你认为这是糟糕的代码吗?请发表评论!非常感谢!

public static void TaskTest(object i)
{
    Console.WriteLine($"{i} Start");

    int count = 1;
    while (true)
    {
        // Open Task to do work
        Task.Run(() => { DoSomeThing(count); });

        var stopWatch = new Stopwatch();
        stopWatch.Start();

        Thread.Sleep(100);

        stopWatch.Stop();
        if (stopWatch.Elapsed.TotalMilliseconds > 200)
        {
            Console.WriteLine($"Id:{count} Time:{DateTime.Now.ToString("HH:mm:ss fff")} " +
            $"ThreadID:{Thread.CurrentThread.ManagedThreadId} Time Delay:{stopWatch.Elapsed.TotalMilliseconds }");
        }

        count++;
    }
}

public static void DoSomeThing(int index)
{
    Thread.Sleep(1000); // Time spent complete work
}

private static void Main(string[] args)
{
    int i = 0;
    while (i < 500)
    {
        // Open Thread for TaskTest
        Thread tesThread = new Thread(TaskTest);
        tesThread.IsBackground = true;
        tesThread.Start(i);
        i++;
    }

    Console.WriteLine("Finish init");
    Console.ReadKey();
}
Run Code Online (Sandbox Code Playgroud)

Bli*_*ndy 5

Task.Delay,像任何其他多线程睡眠函数一样,将它正在运行的线程返回给系统(或者在线程池的情况下,返回给线程池调度程序),要求在一段时间后重新调度指定时间。

这是您拥有的唯一保证,它至少会等待指定的数量。它实际等待的时间在很大程度上取决于您的线程池负载(您在那里延迟了大量任务)、一般系统负载(在任何给定时间点有数千个线程要在普通计算机操作系统上调度)和关于 CPU&OS 快速调度线程的能力(在 Windows 中,请查看timeBeginPeriod)。

长话短说,如果精确的时间对您很重要,请不要放弃您的线程。