Small retreat

Our company uses one very old program with one drawback. After working with it, you need to clean the files behind it and in the same file change the values ​​to the original ones. Otherwise, the next time you start the program does not work correctly.

So the solution - we write the program in the form of a Windows form, and then the form is deleted, and we throw it into autoload. The program runs a timer that checks if that ancient program was closed by the user, he leads the files to its original form.

But I’ve deleted the form this way (users don’t need to know about it), so that my program doesn’t complete the work, it has an endless loop. Here is the code:

private static void Main() { TimerCallback timer= new TimerCallback(Run); System.Threading.Timer time = new System.Threading.Timer(timer, null, 0, 2000); for(;;) } static void Run(object state) {....} 

but as it turned out, it consumes 20-30 percent of the resources of the process precisely because of the infinite cycle. Does anyone have any idea how to reduce the load on the percent?

And I would not like to use the form even if it is completely transparent.

  • And why not stupidly write a program vrapper, which will run the desired program and clean up after it? - VladD
  • write a Windows Service application, using the System.Timers.Timer timer inside, here's an example ru.stackoverflow.com/questions/591163/… - tCode
  • @tCode answer about the service from Yury Bakharev is already present and has undergone some criticism - 4per

4 answers 4

This is your 3-4 cores, so it consumes only 20-30 percent. There will be one core - will eat 100, I think. Put in this cycle at least Sleep (100) and there will be happiness. In general, you need to rewrite normally, and not use crutches ...

  • It helped, instead of a timer, I set it up, and I definitely wouldn’t like to rewrite it about the program. - polsok
  • one
    private static void Main () under DOS wrote? I do not believe - Vladimir Martyanov
  • This is another program for dos written, and I clean it for her. - polsok
  • one
    In general, in principle, the problem is decisive in many ways, for example, 1. Through BAT / PowerShell - the script to which the shortcut is made. The user runs the script, which, in turn, runs the DOS program and waits for it to finish, when completed, cleans the necessary files and copies the file with the required values ​​over the modified one (well, or corrects the values ​​in this file to the required ones). 2. Exactly the same - but through a simple console application. Launcher is made, without any forms and windows (even the console window can be hidden), and visually there is no difference for the user. - BlackWitcher
  • 2
    Look towards WaitForExit and the timer will not be required at all. - BlackWitcher

A program that “drives” the eternal cycle is considered to be hung. This is not the best solution.

So it will be a little better:

 Application.Run(); 

The Run method without parameters starts the message processing cycle (which will lead to the main thread "falling asleep") but it does not specify the main form (allowing the program to work without open forms). At the same time, the program does not lose the ability to correctly process the message of closure (for example, at the end of a user session).

  • 2
    @polsok leave the timer and use this option - the most beautiful solution of those with a minimum of action - 4per
  • @polsok - I also strongly recommend paying attention to this answer (and use a timer). - Alexander Petrov

One of the possible solutions for launching old DOS programs (and not only them) and performing some additional actions is through scripts, the launch of which from the user's point of view will look the same as the launch of the program itself, only the script can also execute some concomitant action. For example, the author of the question needs to delete a number of files after the execution of the program and change the values ​​of the parameters in one of the files.

Let's try to solve the problem using scripts.

Once upon a time I had an IBM PC 286 with an EGA monitor, 40MB hard 5-inch disk (that's right, and another 5 "drive for floppy disk drive) that MS-DOS 6.22 and Norton Commander 4.0 worked on. Since I still remember a little bit how to work with BAT-files , which, however, are very often and successfully used to this day:

 rem Отключаем вывод на экран: @echo off rem Очищаем экран: cls rem Переходим в папку с программой: cd "C:\OLD_PRG\" rem Здесь можно выполнить запуск необходимых программ ДО запуска rem основной программы, например, загрузить русификатор. rem Если запустить его через команду start, то он запустится в отдельном окне. rem Пример: start keyrus.com rem Но нам русификация нужна в этой сессии, потому запускаем его так: keyrus.com rem Теперь запускаем нужную программу и ждем ее завершения: start /wait OldPrg.exe rem Программа завершилась, теперь можно удалить нужные файлы. rem В данном примере это временные файлы *.tmp del *.tmp rem Восстановим файл настроек, для этого просто удалим измененный файл в rem папке программы, а потом заменим эталонным из резервной копии, в rem качестве которой у нас выступает подпапка BAK, находящаяся тут: rem "C:\OLD_PRG\BAK", просто использую относительные пути: del config.cfg copy .\BAK\config.cfg config.cfg rem Всё, теперь можно подождать нажатия любой кнопки, а затем выйти из сессии pause exit 

The script is very simple, is given as an example. In fact, there is much to do with batch files.

The only drawback is that if you create a shortcut to the file directly, then when you launch it, you will see a console window in which our BAT file is running. This is also decidable, because there are utilities that can execute a BAT file hiding the console window in which it runs.


You can also run scripts on PowerShell , but since by default there is a limit in the Windows policy to execute such scripts, I will not consider this option. If it is still very interesting, then it is better to issue it as a separate question.


You can also invoke scripts in other languages, such as JavaScript, or Visual Basic Script.


And, as an option, you can write your own simple wrapper around someone else's EXE, which can be run via Process.Start using WaitForExit . In particular, I myself do this to work with the old console archiver ARJ.


Another option for old DOS programs is, of course, DosBox .

Here, depending on the situation, you can use different approaches to solve the indicated issue of launching old programs in a modern environment.

  • I wonder who slapped the minus ... a simple and affordable solution even for a novice admin, far from programming languages, but a little familiar with the windows console. And no problems with the consumption of resources. - rdorn
  • right here en.wikibooks.org/wiki/Windows_Batch_Scripting is a good cheat sheet for commands in BAT scripts. - rdorn

Well, you can write a service (Windows service) class ServiceBase in.net. Put the code where you clean the file. From the code it is not clear what is happening, the timer is not used at all.

  • one
    Why the service? This is not a service task, it should not work until login. The task for a regular application without Gui. - Vladimir Martyanov
  • one
    And the service can do it too, but writing services and registering them is more difficult. The same can be done at the FS driver level, the only question is why is it difficult to do if it can be done easier? - Vladimir Martyanov
  • one
    Autostart enough. Services have more privileges than they need. - Vladimir Martyanov
  • 3
    Services have as much as they will be given. - Qwertiy
  • one
    the service is not so difficult to be written; here it is installed a little more difficult than to throw the application into autorun - 4per