重定向stdout时,写入stderr以响应Console.CancelKeyPress

时间:2013-12-25 10:26:19

标签: c# .net

当我运行下面的程序并点击ctrl+C时,它会在重定向stdout时写入任何内容。

> .\ConsoleApplication2.exe
Cancelled by user.
> .\ConsoleApplication2.exe > foo.txt
>

有解决办法吗?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.CancelKeyPress += Console_CancelKeyPress;

            Thread.Sleep(TimeSpan.FromMinutes(1));
        }

        static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
        {
            Console.Error.WriteLine("Cancelled by user.");
        }
    }
}

0 个答案:

没有答案