нужно максимально оптимизировать код, потому что жрет очень много памяти
<Grid.ColumnDefinitions>
</Grid.ColumnDefinitions>
Загрузить .txt файлы
Загрузить .magnet файлы
Создать объединённый файл
Сохранить проект
Загрузить проект
<Grid.RowDefinitions>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
</Grid.ColumnDefinitions>
<ListView.View>
<GridViewColumn.CellTemplate>
</GridViewColumn.CellTemplate>
</ListView.View>
<ListView.View>
<GridViewColumn.CellTemplate>
</GridViewColumn.CellTemplate>
</ListView.View>
<DataGrid.Columns>
</DataGrid.Columns>
<Grid.RowDefinitions>
</Grid.RowDefinitions>
using System.Collections.Generic;
using System.Windows;
namespace magnet
{
public partial class SelectFilesWindow : Window
{
public List SelectedFilesSettings { get; private set; } = new List();
private readonly int maxSelection;
code
public SelectFilesWindow(IEnumerable<FileSetting> availableFiles, int maxSelection)
{
InitializeComponent();
FilesListBox.ItemsSource = availableFiles;
this.maxSelection = maxSelection;
}
private void OKButton_Click(object sender, RoutedEventArgs e)
{
if (FilesListBox.SelectedItems.Count != maxSelection)
{
MessageBox.Show($"Выберите ровно {maxSelection} файла(ов) для объединения.", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
foreach (var item in FilesListBox.SelectedItems)
{
if (item is FileSetting fileSetting)
{
SelectedFilesSettings.Add(fileSetting);
}
}
DialogResult = true;
Close();
}
private void CancelButton_Click(object sender, RoutedEventArgs e)
{
DialogResult = false;
Close();
}
}
}
using System.Collections.Generic;
using System.ComponentModel;
Assistant
namespace magnet
{
public class ProjectModel : INotifyPropertyChanged
{
private List txtFiles = new List();
private List magnetFiles = new List();
code
public List<FileSetting> TxtFiles
{
get => txtFiles;
set
{
if (txtFiles != value)
{
txtFiles = value;
OnPropertyChanged(nameof(TxtFiles));
}
}
}
public List<FileSetting> MagnetFiles
{
get => magnetFiles;
set
{
if (magnetFiles != value)
{
magnetFiles = value;
OnPropertyChanged(nameof(MagnetFiles));
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName) =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public class FileSetting : INotifyPropertyChanged
{
private string filePath;
private int linesToSkip;
public string FilePath
{
get => filePath;
set
{
if (filePath != value)
{
filePath = value;
OnPropertyChanged(nameof(FilePath));
}
}
}
public int LinesToSkip
{
get => linesToSkip;
set
{
if (linesToSkip != value)
{
linesToSkip = value;
OnPropertyChanged(nameof(LinesToSkip));
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName) =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public class ProcessedFile
{
public string FileName { get; set; }
public IEnumerable<ProcessedRow> Data { get; set; }
}
public class ProcessedRow : INotifyPropertyChanged
{
private string column2;
private string column3;
private string column4;
private string column5;
public string Column2
{
get => column2;
set
{
if (column2 != value)
{
column2 = value;
OnPropertyChanged(nameof(Column2));
}
}
}
public string Column3
{
get => column3;
set
{
if (column3 != value)
{
column3 = value;
OnPropertyChanged(nameof(Column3));
}
}
}
public string Column4
{
get => column4;
set
{
if (column4 != value)
{
column4 = value;
OnPropertyChanged(nameof(Column4));
}
}
}
public string Column5
{
get => column5;
set
{
if (column5 != value)
{
column5 = value;
OnPropertyChanged(nameof(Column5));
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName) =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
using Microsoft.Win32;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
namespace magnet
{
public partial class MainWindow : Window
{
private ProjectModel currentProject = new ProjectModel();
private FileSetting selectedFile = null;
private const int MaxPreviewLines = 1000;
code
public MainWindow()
{
InitializeComponent();
TxtFilesListView.ItemsSource = currentProject.TxtFiles;
MagnetFilesListView.ItemsSource = currentProject.MagnetFiles;
}
private async void LoadTxtFilesButton_Click(object sender, RoutedEventArgs e)
{
await LoadFilesAsync(".txt", currentProject.TxtFiles, TxtFilesListView);
}
private async void LoadMagnetFilesButton_Click(object sender, RoutedEventArgs e)
{
await LoadFilesAsync(".magnet", currentProject.MagnetFiles, MagnetFilesListView);
}
private async Task LoadFilesAsync(string extension, List<FileSetting> fileCollection, ListView listView)
{
OpenFileDialog dlg = new OpenFileDialog
{
Multiselect = true,
Filter = $"Файлы {extension}|*{extension}"
};
bool? result = dlg.ShowDialog();
if (result == true)
{
var newFiles = dlg.FileNames
.Where(filename => !fileCollection.Any(f => string.Equals(f.FilePath, filename, StringComparison.OrdinalIgnoreCase)))
.ToList();
if (newFiles.Any())
{
foreach (string filename in newFiles)
{
fileCollection.Add(new FileSetting { FilePath = filename, LinesToSkip = 0 });
}
listView.SelectedItem = fileCollection.Last();
}
else
{
MessageBox.Show("Все выбранные файлы уже добавлены.", "Информация", MessageBoxButton.OK, MessageBoxImage.Information);
}
}
}
private async void TxtFilesListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (TxtFilesListView.SelectedItem is FileSetting selected)
{
selectedFile = selected;
LinesToSkipTextBox.Text = selected.LinesToSkip.ToString();
MagnetFilesListView.SelectedItem = null;
await PreviewFileAsync(selected);
}
else
{
ClearPreview();
}
}
private async void MagnetFilesListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (MagnetFilesListView.SelectedItem is FileSetting selected)
{
selectedFile = selected;
LinesToSkipTextBox.Text = selected.LinesToSkip.ToString();
TxtFilesListView.SelectedItem = null;
await PreviewFileAsync(selected);
}
else
{
ClearPreview();
}
}
private void ClearPreview()
{
selectedFile = null;
PreviewDataGrid.ItemsSource = null;
LinesToSkipTextBox.Text = "0";
}
private async Task PreviewFileAsync(FileSetting fileSetting)
{
if (!File.Exists(fileSetting.FilePath))
{
ClearPreview();
MessageBox.Show($"Файл не найден: {fileSetting.FilePath}", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
try
{
var data = new List<PreviewRow>();
int maxColumns = 0;
using (var reader = new StreamReader(fileSetting.FilePath))
{
for (int i = 0; i < fileSetting.LinesToSkip; i++)
{
if (await reader.ReadLineAsync() == null)
break;
}
string line;
int count = 0;
while ((line = await reader.ReadLineAsync()) != null && count < MaxPreviewLines)
{
var columns = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
if (columns.Length > maxColumns)
maxColumns = columns.Length;
// Используем конструктор PreviewRow
data.Add(new PreviewRow(columns.ToList()));
count++;
}
}
Dispatcher.Invoke(() =>
{
PreviewDataGrid.Columns.Clear();
for (int i = 0; i < maxColumns; i++)
{
PreviewDataGrid.Columns.Add(new DataGridTextColumn
{
Header = $"Столбец {i + 1}",
Binding = new System.Windows.Data.Binding($"Columns[{i}]"),
Width = 100
});
}
PreviewDataGrid.ItemsSource = data;
this.Title = $"Magnet File Previewer - {Path.GetFileName(fileSetting.FilePath)} (Предпросмотр {data.Count} строк)";
});
}
catch (Exception ex)
{
ClearPreview();
MessageBox.Show($"Ошибка при чтении файла: {ex.Message}", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
private async void UpdateLinesToSkip_Click(object sender, RoutedEventArgs e)
{
if (selectedFile != null)
{
if (int.TryParse(LinesToSkipTextBox.Text, out int skip) && skip >= 0)
{
selectedFile.LinesToSkip = skip;
await PreviewFileAsync(selectedFile);
RefreshListView(selectedFile);
}
else
{
MessageBox.Show("Введите корректное неотрицательное число строк для пропуска.", "Ошибка ввода", MessageBoxButton.OK, MessageBoxImage.Warning);
}
}
else
{
MessageBox.Show("Выберите файл для обновления.", "Предупреждение", MessageBoxButton.OK, MessageBoxImage.Warning);
}
}
private void RefreshListView(FileSetting file)
{
if (file.FilePath.EndsWith(".txt", StringComparison.OrdinalIgnoreCase))
{
var index = currentProject.TxtFiles.IndexOf(file);
if (index >= 0)
{
currentProject.TxtFiles[index] = file;
TxtFilesListView.Items.Refresh();
}
}
else if (file.FilePath.EndsWith(".magnet", StringComparison.OrdinalIgnoreCase))
{
var index = currentProject.MagnetFiles.IndexOf(file);
if (index >= 0)
{
currentProject.MagnetFiles[index] = file;
MagnetFilesListView.Items.Refresh();
}
}
}
private void SaveProjectButton_Click(object sender, RoutedEventArgs e)
{
if (!currentProject.TxtFiles.Any() && !currentProject.MagnetFiles.Any())
{
MessageBox.Show("Нет файлов для сохранения проекта.", "Предупреждение", MessageBoxButton.OK, MessageBoxImage.Warning);
return;
}
SaveFileDialog dlg = new SaveFileDialog
{
Filter = "Magnet Project Files (*.magn)|*.magn",
DefaultExt = "magn",
FileName = "project.magn"
};
bool? result = dlg.ShowDialog();
if (result == true)
{
try
{
string json = JsonConvert.SerializeObject(currentProject, Formatting.Indented);
File.WriteAllText(dlg.FileName, json);
MessageBox.Show("Проект успешно сохранён!", "Успех", MessageBoxButton.OK, MessageBoxImage.Information);
}
catch (Exception ex)
{
MessageBox.Show($"Ошибка при сохранении проекта: {ex.Message}", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
}
private async void LoadProjectButton_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog
{
Filter = "Magnet Project Files (*.magn)|*.magn",
DefaultExt = "magn"
};
bool? result = dlg.ShowDialog();
if (result == true)
{
try
{
string json = await File.ReadAllTextAsync(dlg.FileName);
ProjectModel loadedProject = JsonConvert.DeserializeObject<ProjectModel>(json);
if (loadedProject != null)
{
currentProject.TxtFiles = loadedProject.TxtFiles ?? new List<FileSetting>();
currentProject.MagnetFiles = loadedProject.MagnetFiles ?? new List<FileSetting>();
TxtFilesListView.ItemsSource = currentProject.TxtFiles;
MagnetFilesListView.ItemsSource = currentProject.MagnetFiles;
TxtFilesListView.Items.Refresh();
MagnetFilesListView.Items.Refresh();
ClearPreview();
MessageBox.Show("Проект успешно загружен!", "Успех", MessageBoxButton.OK, MessageBoxImage.Information);
}
else
{
MessageBox.Show("Не удалось загрузить проект.", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
catch (Exception ex)
{
MessageBox.Show($"Ошибка при загрузке проекта: {ex.Message}", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
}
private async void CreateCombinedFileButton_Click(object sender, RoutedEventArgs e)
{
if (currentProject.TxtFiles.Count < 2)
{
MessageBox.Show("Необходимо загрузить минимум два .txt файла для объединения.", "Предупреждение", MessageBoxButton.OK, MessageBoxImage.Warning);
return;
}
SelectFilesWindow selectFilesWindow = new SelectFilesWindow(currentProject.TxtFiles, 2);
if (selectFilesWindow.ShowDialog() == true)
{
List<FileSetting> selectedTxtFiles = selectFilesWindow.SelectedFilesSettings;
if (selectedTxtFiles.Count != 2)
{
MessageBox.Show("Выберите ровно два файла для объединения.", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
try
{
string combinedFileName = $"Combined_{DateTime.Now:yyyyMMdd_HHmmss}.magn";
ProcessedFile processedFile = new ProcessedFile
{
FileName = combinedFileName,
Data = ReadAndCombineFiles(selectedTxtFiles)
};
if (!processedFile.Data.Any())
{
MessageBox.Show("Объединённые файлы не содержат данных для объединения.", "Информация", MessageBoxButton.OK, MessageBoxImage.Information);
return;
}
AddProcessedFileTab(processedFile);
}
catch (Exception ex)
{
MessageBox.Show($"Ошибка при объединении файлов: {ex.Message}", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
}
private IEnumerable<ProcessedRow> ReadAndCombineFiles(List<FileSetting> files)
{
foreach (var file in files)
{
using (var reader = new StreamReader(file.FilePath))
{
// Пропуск строк
for (int i = 0; i < file.LinesToSkip; i++)
{
if (reader.ReadLine() == null)
break;
}
string line;
while ((line = reader.ReadLine()) != null)
{
if (string.IsNullOrWhiteSpace(line))
continue;
string[] columns = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
if (columns.Length < 5)
{
MessageBox.Show($"Файл {file.FilePath} содержит строку с недостаточным количеством столбцов: {line}", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
yield break;
}
string formattedTime = "00:00:00";
if (double.TryParse(columns[4], out double originalValue))
{
double divided = originalValue / 24.0;
TimeSpan time = TimeSpan.FromHours(divided);
formattedTime = time.ToString(@"hh\:mm\:ss");
}
yield return new ProcessedRow
{
Column2 = columns[1],
Column3 = columns[2],
Column4 = columns[3],
Column5 = formattedTime
};
}
}
}
}
private void AddProcessedFileTab(ProcessedFile processedFile)
{
DataGrid dataGrid = new DataGrid
{
AutoGenerateColumns = false,
IsReadOnly = true,
CanUserAddRows = false,
ItemsSource = processedFile.Data,
Margin = new Thickness(5),
EnableRowVirtualization = true,
EnableColumnVirtualization = true
};
dataGrid.Columns.Add(new DataGridTextColumn { Header = "Столбец 1", Binding = new System.Windows.Data.Binding("Column2"), Width = 150 });
dataGrid.Columns.Add(new DataGridTextColumn { Header = "Столбец 2", Binding = new System.Windows.Data.Binding("Column3"), Width = 150 });
dataGrid.Columns.Add(new DataGridTextColumn { Header = "Столбец 3", Binding = new System.Windows.Data.Binding("Column4"), Width = 150 });
dataGrid.Columns.Add(new DataGridTextColumn { Header = "Столбец 4", Binding = new System.Windows.Data.Binding("Column5"), Width = 100 });
Button saveButton = new Button
{
Content = "Сохранить файл",
Width = 120,
Height = 30,
Margin = new Thickness(5)
};
saveButton.Click += (s, e) => SaveProcessedFile(processedFile);
StackPanel stackPanel = new StackPanel();
stackPanel.Children.Add(dataGrid);
stackPanel.Children.Add(saveButton);
TabItem tabItem = new TabItem
{
Header = processedFile.FileName,
Content = stackPanel
};
ProcessedFilesTabControl.Items.Add(tabItem);
ProcessedFilesTabControl.SelectedItem = tabItem;
}
private async void SaveProcessedFile(ProcessedFile processedFile)
{
SaveFileDialog dlg = new SaveFileDialog
{
Filter = "Magnet Files (*.magn)|*.magn",
DefaultExt = "magn",
FileName = processedFile.FileName
};
bool? result = dlg.ShowDialog();
if (result == true)
{
try
{
using (var writer = new StreamWriter(dlg.FileName))
{
await writer.WriteLineAsync("Столбец 1\tСтолбец 2\tСтолбец 3\tСтолбец 4");
foreach (var row in processedFile.Data)
{
string line = $"{row.Column2}\t{row.Column3}\t{row.Column4}\t{row.Column5}";
await writer.WriteLineAsync(line);
}
}
MessageBox.Show("Файл успешно сохранён!", "Успех", MessageBoxButton.OK, MessageBoxImage.Information);
}
catch (Exception ex)
{
MessageBox.Show($"Ошибка при сохранении файла: {ex.Message}", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
}
}
public class PreviewRow : INotifyPropertyChanged
{
private readonly List<string> columns;
public PreviewRow(List<string> columns)
{
this.columns = columns;
}
public List<string> Columns => columns;
public event PropertyChangedEventHandler PropertyChanged;
}
}
Оптимизация использования памяти в вашем приложении WPF может значительно повысить производительность и снизить нагрузку на систему. Ниже представлены рекомендации и обновлённый код с учётом оптимизаций, направленных на уменьшение потребления памяти.
1. Использование ObservableCollection вместо List
ObservableCollection предоставляет встроенные уведомления об изменениях коллекции, что упрощает и оптимизирует привязку данных в WPF. Это позволяет избежать частого обновления элементов списка вручную и снижает нагрузку на память.
Обновлённая ProjectModel:
csharp
using System.Collections.ObjectModel;
using System.ComponentModel;
namespace magnet
{
public class ProjectModel : INotifyPropertyChanged
{
public ObservableCollection<FileSetting> TxtFiles { get; } = new ObservableCollection<FileSetting>();
public ObservableCollection<FileSetting> MagnetFiles { get; } = new ObservableCollection<FileSetting>();
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName) =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
2. Оптимизация класса PreviewRow
Использование массива строк вместо списка сокращает объём потребляемой памяти. Кроме того, удаление интерфейса INotifyPropertyChanged из класса, если свойства неизменяемы, снижает накладные расходы.
Обновлённый PreviewRow:
csharp
namespace magnet
{
public class PreviewRow
{
public string[] Columns { get; }
public PreviewRow(string[] columns)
{
Columns = columns;
}
}
}
3. Оптимизация класса ProcessedRow
Если данные не изменяются после создания, можно сделать свойства только для чтения и убрать INotifyPropertyChanged, что уменьшит потребление памяти.
Обновлённый ProcessedRow:
csharp
namespace magnet
{
public class ProcessedRow
{
public string Column2 { get; }
public string Column3 { get; }
public string Column4 { get; }
public string Column5 { get; }
public ProcessedRow(string column2, string column3, string column4, string column5)
{
Column2 = column2;
Column3 = column3;
Column4 = column4;
Column5 = column5;
}
}
}
4. Оптимизация метода PreviewFileAsync
Предварительное выделение памяти для списка и использование массивов вместо списков помогают снизить фрагментацию памяти и ускорить выполнение.
Обновлённый PreviewFileAsync:
csharp
private async Task PreviewFileAsync(FileSetting fileSetting)
{
if (!File.Exists(fileSetting.FilePath))
{
ClearPreview();
MessageBox.Show($"Файл не найден: {fileSetting.FilePath}", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
try
{
var data = new List<PreviewRow>(MaxPreviewLines);
int maxColumns = 0;
using (var reader = new StreamReader(fileSetting.FilePath))
{
for (int i = 0; i < fileSetting.LinesToSkip; i++)
{
if (await reader.ReadLineAsync() == null)
break;
}
string line;
int count = 0;
while ((line = await reader.ReadLineAsync()) != null && count < MaxPreviewLines)
{
var columns = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
int columnCount = columns.Length;
if (columnCount > maxColumns)
maxColumns = columnCount;
if (columnCount > 0)
{
var columnsArray = new string[columnCount];
Array.Copy(columns, columnsArray, columnCount);
data.Add(new PreviewRow(columnsArray));
count++;
}
}
}
await Dispatcher.InvokeAsync(() =>
{
PreviewDataGrid.Columns.Clear();
for (int i = 0; i < maxColumns; i++)
{
PreviewDataGrid.Columns.Add(new DataGridTextColumn
{
Header = $"Столбец {i + 1}",
Binding = new System.Windows.Data.Binding($"Columns[{i}]"),
Width = 100
});
}
PreviewDataGrid.ItemsSource = data;
this.Title = $"Magnet File Previewer - {Path.GetFileName(fileSetting.FilePath)} (Предпросмотр {data.Count} строк)";
});
}
catch (Exception ex)
{
ClearPreview();
MessageBox.Show($"Ошибка при чтении файла: {ex.Message}", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
5. Оптимизация метода ReadAndCombineFiles
Избегайте отображения сообщений об ошибках внутри генератора данных. Вместо этого собирайте ошибки и отображайте их после завершения обработки, что предотвращает блокировку процесса и снижает нагрузку на память.
Обновлённый ReadAndCombineFiles:
csharp
private IEnumerable<ProcessedRow> ReadAndCombineFiles(IEnumerable<FileSetting> files, out List<string> errors)
{
errors = new List<string>();
foreach (var file in files)
{
using (var reader = new StreamReader(file.FilePath))
{
for (int i = 0; i < file.LinesToSkip; i++)
{
if (reader.ReadLine() == null)
break;
}
string line;
while ((line = reader.ReadLine()) != null)
{
if (string.IsNullOrWhiteSpace(line))
continue;
string[] columns = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
if (columns.Length < 5)
{
errors.Add($"Файл {file.FilePath} содержит строку с недостаточным количеством столбцов: {line}");
continue;
}
string formattedTime = "00:00:00";
if (double.TryParse(columns[4], out double originalValue))
{
double divided = originalValue / 24.0;
TimeSpan time = TimeSpan.FromHours(divided);
formattedTime = time.ToString(@"hh\:mm\:ss");
}
yield return new ProcessedRow(
columns[1],
columns[2],
columns[3],
formattedTime);
}
}
}
}
Обновлённый метод CreateCombinedFileButton_Click:
csharp
private async void CreateCombinedFileButton_Click(object sender, RoutedEventArgs e)
{
if (currentProject.TxtFiles.Count < 2)
{
MessageBox.Show("Необходимо загрузить минимум два .txt файла для объединения.", "Предупреждение", MessageBoxButton.OK, MessageBoxImage.Warning);
return;
}
SelectFilesWindow selectFilesWindow = new SelectFilesWindow(currentProject.TxtFiles, 2);
if (selectFilesWindow.ShowDialog() == true)
{
List<FileSetting> selectedTxtFiles = selectFilesWindow.SelectedFilesSettings;
if (selectedTxtFiles.Count != 2)
{
MessageBox.Show("Выберите ровно два файла для объединения.", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
try
{
string combinedFileName = $"Combined_{DateTime.Now:yyyyMMdd_HHmmss}.magn";
List<string> errors;
var processedData = ReadAndCombineFiles(selectedTxtFiles, out errors).ToList();
if (errors.Any())
{
MessageBox.Show(string.Join(Environment.NewLine, errors), "Ошибки при обработке", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
string filePath = Path.Combine(Environment.CurrentDirectory, combinedFileName);
ProcessedFile processedFile = new ProcessedFile
{
FileName = combinedFileName,
Data = processedData
};
AddProcessedFileTab(processedFile);
}
catch (Exception ex)
{
MessageBox.Show($"Ошибка при объединении файлов: {ex.Message}", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
}
6. Управление вкладками обработанных файлов
Создание большого количества вкладок с DataGrid может привести к увеличению потребления памяти. Рассмотрите возможность ограничения количества открытых вкладок или предоставьте пользователю возможность закрывать ненужные вкладки.
Обновлённый AddProcessedFileTab с ограничением количества вкладок:
Профилирование памяти: Используйте инструменты профилирования (например, встроенные средства Visual Studio или JetBrains dotMemory) для выявления утечек памяти и определения точных мест их возникновения.
Освобождение ресурсов: Убедитесь, что все потоковые ресурсы (например, StreamReader, StreamWriter) корректно освобождаются после использования с помощью using или явных вызовов Dispose.
Ленивые загрузки и виртуализация: Рассмотрите возможность реализации ленивой загрузки данных или расширенной виртуализации для контролов, работающих с большой объёмом данных.
Минимизация привязок: Избегайте сложных и частых привязок данных, которые могут приводить к увеличенному потреблению памяти и замедлению интерфейса.
Оптимизация XAML: Убедитесь, что в XAML используются ресурсы и стили эффективно, избегая избыточных слоёв элементов и сложных визуальных деревьев.
Итог
Применив вышеописанные оптимизации, ваше приложение должно потреблять меньше оперативной памяти, работать быстрее и быть более отзывчивым. Кроме того, регулярное профилирование поможет вам отслеживать и устранять потенциальные проблемы с производительностью и использованием ресурсов в будущем.
Если у вас есть дополнительные вопросы или требуется дальнейшая помощь, не стесняйтесь обращаться!
Not yet included in a published release.
Примените стиль к вашим TabItem и реализуйте обработчик CloseTab_Click: