There is a class below:

public static void ProcessWatch_Initialize() { try { ManagementScope scope = new ManagementScope("root\\CIMV2"); scope.Options.EnablePrivileges = true; WqlEventQuery query = new WqlEventQuery("Select * From __InstanceCreationEvent Within 1 Where TargetInstance ISA 'Win32_DiskDrive'"); watcher = new ManagementEventWatcher(scope, query); watcher.EventArrived += new EventArrivedEventHandler(watcher_EventArrived); watcher.Start(); Console.ReadLine(); } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { if (watcher != null) watcher.Stop(); } } 

Everything seems to work and everything is fine, but there is one thing, but if you remove Console.ReadLine() after running the watcher , does the code stop working? How to deal with it?

    2 answers 2

    In principle, it is logical. If you remove Console.ReadLine(); , the try block will be executed first, which will start the watcher , and then the finally block, which will stop it, since will be executed in any case.

    You can try this:

     try { // тут код с запуском watcher while (Console.ReadLine() != "stop") { } watcher.Stop(); } catch (Exception ex) { Console.WriteLine(ex.Message); if (watcher != null) watcher.Stop(); Console.ReadKey(); } 

    Until we enter the word stop , watcher will continue to work.

    • To be honest, I didn’t even know or even assumed the purpose of the finally element. - Alex

    The problem was solved as follows: I had to add return; after watcher.Start();

    as well as remove

     finally { if (watcher != null) watcher.Stop(); }