У меня есть приложение, которое позволяет пользователям загружать выбранные изображения в DataGridView и выполнять операции над ними. Однако, когда выбрано несколько изображений, форма останавливается до тех пор, пока информация об изображении не будет загружена в DataGridView. Я пробовал BackgroundWorker для этого, но он тоже не работает. Мои коды выглядят так:
private void button1_Click(object sender, EventArgs e)
{
var file = new OpenFileDialog
{
Filter = @"TIFF |*.tiff| TIF|*.tif",
FilterIndex = 1,
Title = @"Select TIFF file(s)...",
Multiselect = true
};
if (file.ShowDialog() == DialogResult.OK)
{
Listing(file.FileNames);
}
}
private void Listing(string[] files)
{
foreach (var file in files)
{
var pic_name = Path.GetFileName(file);
if (file != null)
{
// Image from file
var img = Image.FromFile(file);
// Get sizes of TIFF image
var pic_sizes = img.Width + " x " + img.Height;
// Get size of TIFF image
var pic_size = new FileInfo(file).Length;
//Create the new row first and get the index of the new row
var rowIndex = dataGridView1.Rows.Add();
//Obtain a reference to the newly created DataGridViewRow
var row = dataGridView1.Rows[rowIndex];
//Now this won't fail since the row and columns exist
row.Cells["name"].Value = pic_name;
row.Cells["sizes"].Value = pic_sizes + " pixels";
row.Cells["size"].Value = pic_size + " bytes";
}
}
}
Как я могу решить эту проблему?
РЕДАКТИРОВАТЬ: После комментария Алекса я попробовал так:
private void button1_Click(object sender, EventArgs e)
{
var file = new OpenFileDialog
{
Filter = @"TIFF |*.tiff| TIF|*.tif",
FilterIndex = 1,
Title = @"Select TIFF file(s)...",
Multiselect = true
};
if (file.ShowDialog() == DialogResult.OK)
{
_ = Test(file.FileNames);
}
}
private async Task Test(string[] s)
{
await Task.Run(() => Listing(s));
}
private void Listing(string[] files)
{
BeginInvoke((MethodInvoker) delegate
{
foreach (var file in files)
{
var pic_name = Path.GetFileName(file);
if (file != null)
{
// Image from file
var img = Image.FromFile(file);
// Get sizes of TIFF image
var pic_sizes = img.Width + " x " + img.Height;
// Get size of TIFF image
var pic_size = new FileInfo(file).Length;
//Create the new row first and get the index of the new row
var rowIndex = dataGridView1.Rows.Add();
//Obtain a reference to the newly created DataGridViewRow
var row = dataGridView1.Rows[rowIndex];
//Now this won't fail since the row and columns exist
row.Cells["name"].Value = pic_name;
row.Cells["sizes"].Value = pic_sizes + " pixels";
row.Cells["size"].Value = pic_size + " bytes";
}
}
});
}
Но, к сожалению, результат тот же.