小编tad*_*tad的帖子

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

在 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 …
Run Code Online (Sandbox Code Playgroud)

c# multithreading task delay async-await

0
推荐指数
1
解决办法
227
查看次数

标签 统计

async-await ×1

c# ×1

delay ×1

multithreading ×1

task ×1