Answer the question
In order to leave comments, you need to log in
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();
}
}
}
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();
}
}
Answer the question
In order to leave comments, you need to log in
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);
}
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question