S
S
s2d1ent2021-08-22 01:05:36
C++ / C#
s2d1ent, 2021-08-22 01:05:36

How to solve the quick closing of the program?

Hello fellow programmers. Faced such a problem that when you start the program, it quickly closes, now I will explain

using System;
using System.Collections.Generic;

namespace System.Finder
{
    class Program
    {
        // список томов на ПК
        public List<Directory> Directories = new List<Directory>();
        static void Main(string[] args)
        {
            // инициализация сканирования
            Directory d = new Directory(true);
            Console.ReadKey();
        }
    }
}


This is the main project file in which initialization takes place and, in principle, everything, nothing else is done in it, all other program actions are described in another file and are done automatically with ReadKey (in Main). But if you remove ReadKey (from Main), then the program will instantly collapse, if you remove ReadKey and run the program in the background, the same thing will happen.

public Directory() { }
        public Directory(bool th)
        {
            Scan();
        }
        public Directory(string name, string adress)
        {
            this.name = name;
            this.adress = adress;
            new Task(()=> { Start(); }).Start();
        }
        // сканирование томов ПК
        public void Scan()
        {
            DriveInfo[] drivers = DriveInfo.GetDrives();
            foreach (var driver in drivers)
            {
                new Task(()=> { new Program().Directories.Add(new Directory(driver.Name, driver.ToString())); }).Start();
            }
        }

This is a piece of code from the second file, it starts to do all the other actions, please don't hit me if I write something crookedly, the experience is small, it's better to just explain what I'm doing wrong. The second file describes the functions to get started with and recursive functions that are executed up to a certain point.
Link to Git , perhaps it will be clearer this way (test branch).

Answer the question

In order to leave comments, you need to log in

2 answer(s)
B
Boris the Animal, 2021-08-22
@s2d1ent

This is how you can write a scanner class that receives data asynchronously. It can be used in this way in any type of application. For example, in WPF, the application will not hang if, say, a scan is started on a button click.
Also pay attention to the method with Task.Factory.StartNew and the TaskCreationOptions.LongRunning parameter. For scanning folders, I think it's worth using.

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

namespace ConsoleApp
{
    class Program
    {
        static async Task Main(string[] args)
        {
            try
            {
                // Создаём экземпляр класса
                var scanner = new Scanner();
                // Вызываем асинхронный метод Scan, метод работает
                // какое-то время, возвращает результат.
                var data = await scanner.Scan();
                foreach (var item in data)
                {
                    // Выводим на консоль.
                    Console.WriteLine(item);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
    }

    public class Scanner
    {
        public Task<List<string>> Scan()
        {
            return Task.Run(async () =>
            {
                var results = new List<string>();

                for (int i = 0; i < 10; i++)
                {
                    // Делаем правильную задержку (имитация долгой работы для примера).
                    await Task.Delay(250);
                    // Собираем данные
                    results.Add(DateTimeOffset.Now.ToLocalTime().ToString());
                }

                return results;
            });
        }

        public async Task<List<string>> ScanVersion2()
        {
            return await Task.Factory.StartNew(async () =>
            {
                var results = new List<string>();

                for (int i = 0; i < 10; i++)
                {
                    // Делаем правильную задержку (имитация долгой работы для примера).
                    await Task.Delay(250);
                    // Собираем данные
                    results.Add(DateTimeOffset.Now.ToLocalTime().ToString());
                }

                return results;
            }, TaskCreationOptions.LongRunning)
                .Unwrap() // Без этого возвращается Task<List<string>>, а не List<string>
                .ConfigureAwait(false);
        }
    }
}

It is worth reading the book " Concurrency in C #. Asynchronous, parallel and multithreaded programming "
Screenshot taken from the video: https://youtu.be/lh8cT6qI-nA?t=1123
612185e7a4563153795281.jpeg

D
Developer, 2021-08-22
@samodum

Learn how Main() works and everything will become clear to you . Have you
read books?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question