如何让这个基于事件的控制台应用程序不立即终止?

mpe*_*pen 17 c# events filesystemwatcher

资源

class Program
{
    static void Main(string[] args)
    {
        var fw = new FileSystemWatcher(@"M:\Videos\Unsorted");
        fw.Created+= fw_Created;
    }

    static void fw_Created(object sender, FileSystemEventArgs e)
    {
        Console.WriteLine("added file {0}", e.Name);
    }
}
Run Code Online (Sandbox Code Playgroud)

应该是非常自我解释.我正在尝试创建一个文件监视器,以便我可以自动为我排序视频...如何让程序无法终止?

我想保持它基于控制台,所以我可以调试它,但最终我想删除控制台,只是让它在后台运行(我想作为一项服务).

M.B*_*ock 22

也许是这样的:

class Program
{
    static void Main(string[] args)
    {
        var fw = new FileSystemWatcher(@"M:\Videos\Unsorted");
        fw.Changed += fw_Changed;
        fw.EnableRaisingEvents = true;

        new System.Threading.AutoResetEvent(false).WaitOne();
    }

    static void fw_Changed(object sender, FileSystemEventArgs e)
    {
        Console.WriteLine("added file {0}", e.Name);
    }
}
Run Code Online (Sandbox Code Playgroud)

更新

本着帮助其他可能寻找类似解决方案的人的精神,正如@Mark在评论中所说,还有一种方法可以使用类的WaitForChanged方法FileSystemWatcher来解决这个问题:

class Program
{
    static void Main(string[] args)
    {
        var fw = new FileSystemWatcher(@".");
        while (true)
        {
            Console.WriteLine("added file {0}",
                fw.WaitForChanged(WatcherChangeTypes.All).Name);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这样做允许应用程序无限期地等待(或者直到时间被破坏)才能更改文件.

  • 设置事件处理程序后,需要将EnableRaisingEvents设置为true.我已经更新了答案以显示如何.有关更多信息,请查看FileSystemWatcher文档中的示例:http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.aspx (3认同)

mpe*_*pen 7

class Program
{
    static void Main(string[] args)
    {
        var fw = new FileSystemWatcher(@"M:\Videos\Unsorted");
        fw.EnableRaisingEvents = true;
        fw.Created += fw_Created;

        Console.ReadLine();

    }

    static void fw_Created(object sender, FileSystemEventArgs e)
    {
        Console.WriteLine("added file {0}", e.Name);
    }

}
Run Code Online (Sandbox Code Playgroud)

只是EnableRaisingEvents显然.


找到了另一个可能更好的解决方案:

class Program
{
    static void Main(string[] args)
    {
        var fw = new FileSystemWatcher(@"M:\Videos\Unsorted");
        fw.Created += fw_Created;
        while(true) fw.WaitForChanged(WatcherChangeTypes.All);
    }

    static void fw_Created(object sender, FileSystemEventArgs e)
    {
        Console.WriteLine("added file {0}", e.Name);
    }
}
Run Code Online (Sandbox Code Playgroud)