Console.Writeline是否异步运行

时间:2016-11-18 12:47:21

标签: stopwatch

我正在测试将二进制转换为字符串所需的速度,以确定它是否会成为瓶颈。问题是,控制台窗口的完成时间比计时器建议要长......

简单地说,应用程序运行大约需要10秒钟(GUI正在更新大约4-5秒,并且更新发生在计时器启动和计时器停止调用内)但它总是显示它只需要大约1秒钟。

这是要复制的完整代码

class Program
{
    static List<int[]> binary = new List<int[]>();
    static void Main()
    {
        for (int i = 0; i < 5000; i++)
        {
            Add();    //creates the list to convert. I don't need to time this as it's only populating the list
        }
        Stopwatch sw = new Stopwatch();
        sw.Start();
        Console.WriteLine("start");
        foreach (var item in binary)
        {
            var h = item;
            int result = 0;
            int bitValue = 1;

            for (int i = h.Length - 1; i >= 0; i--)
            {
                result += h[i] * bitValue;
                bitValue *= 2;
            }

            Console.WriteLine((char)result);
        }

        sw.Stop();

        Console.WriteLine("Done in " + new TimeSpan(sw.ElapsedTicks).TotalSeconds);

        Console.ReadKey();
    }

    private static void Add()
    {
        binary.Add(new int[] { 0, 1, 0, 1, 0, 0, 1, 1 });
        binary.Add(new int[] { 0, 1, 0, 1, 0, 1, 0, 0 });
        binary.Add(new int[] { 0, 1, 0, 1, 0, 0, 1, 0 });
        binary.Add(new int[] { 1, 1, 0, 1, 0, 0, 1, 1 });
        binary.Add(new int[] { 1, 1, 0, 1, 0, 0, 1, 1 });
    }

当我可以计算GUI完成更新所需的时间(4-5秒)时,为什么计时器显示1秒? Console.WriteLine在计时器内部,我不相信它以异步方式发送到屏幕,但它似乎是以这种方式表现?

1 个答案:

答案 0 :(得分:0)

因为在运行Add()操作5000次后启动秒表......这需要时间。

相关问题