- [DEVEXPRESS] Chia sẻ code các tạo report in nhiều hóa đơn trên XtraReport C#
- [POWER AUTOMATE] Hướng dẫn gởi tin nhắn zalo từ file Excel - No code
- [C#] Chia sẻ code lock và unlock user trong domain Window
- [SOFTWARE] Giới thiệu bộ phần mềm tính Kết Cấu Thép HatteSale, Mộng Đơn, Dầm, Sàn, Móng Cọc, Vách, Xà Gồ, Tính Tải Trọng
- [DEVEXPRESS] Vẽ Biểu Đồ Stock Chứng Khoán - Công Cụ Thiết Yếu Cho Nhà Đầu Tư trên Winform
- [C#] Hướng dẫn bảo mật ứng dụng 2FA (Multi-factor Authentication) trên Winform
- [C#] Hướng dẫn convert HTML code sang PDF File trên NetCore 7 Winform
- [C#] Hướng dẫn viết ứng dụng chat với Gemini AI Google Winform
- Hướng dẫn khóa file bằng nhiều process id, không cho xóa tập tin
- Hướng dẫn cách tạo Product Id cho ứng dụng phần mềm XXXXX-XXXXX-XXXXX-XXXXX
- [SQLSERVER] Hướng dẫn tạo script sql từ ứng dụng Sqlserver management Studio
- [C#] Hướng dẫn sử dụng thư viện AutoITx lấy id và password Ultraviewer trên winform
- [VB.NET] Hướng dẫn lấy thông tin tài khoản đăng nhập windows và khởi động lại ứng dụng ở chế độ Administrator
- [C#] Sử dụng thư viện Polly gửi lại request api khi request bị lỗi hay rớt mạng
- [DEVEXPRESS] Chia sẻ source code tạo báo cáo report in tem nhãn label trên C# winform
- [DEVEXPRESS] Hướng dẫn vẽ biểu đồ Bar Chart trên Winform
- [C#] Tạo form đăng nhập và đăng ký với hiệu ứng Sliding Animation Effect
- [C#] Hướng dẫn tạo thanh toán đơn hàng qua mã vạch VietQR sử dụng API PayOS hoàn toàn miễn phí
- [C#] Hướng dẫn ghi log ra RichTextBox giống Console trên Winform sử dụng thư viện Serilog
- [C#] Hướng dẫn cách tạo mã QR Code trên file Excel
[C#] Tạo hình ảnh thumbnail hàng loạt so sánh sử dụng bất đồng bộ và Parallel Async
Xin chào các bạn, bài viết hôm nay mình sẽ hướng dẫn các bạn các chuyển đổi hàng loạt hình ảnh gốc (original) sang hình ảnh thumbnail sử dụng Parallel C#.
Ở bài viết này, ngoài cách chuyển đổi hình ảnh thumnail hàng loạt.
Mình còn muốn hướng dẫn cho các bạn thấy cách sử dụng Parallel để vận dụng tối đa sức mạnh của phần cứng CPU.
Các bạn có thể xem video ở dưới đây, để có thể thấy được sự khác biệt khi sử dụng Parallel và khi không sử dụng Parallel.
Video demo ứng dụng:
Trong bài viết này, mình sử dụng bất động bộ và có trả về phần trăm kết quả thực thi, các file đang thực thi.
Các bạn có thể xem code ở bên dưới, hoặc download project về để tham khảo.
Source code Parallel convert image origin to thumbnail C#:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Thumbnails
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btn_input_Click(object sender, EventArgs e)
{
var dlg = new FolderBrowserDialog();
if (dlg.ShowDialog() == DialogResult.OK)
{
txt_input.Text = dlg.SelectedPath;
}
}
private void btn_output_Click(object sender, EventArgs e)
{
var dlg = new FolderBrowserDialog();
if (dlg.ShowDialog() == DialogResult.OK)
{
txt_output.Text = dlg.SelectedPath;
}
}
int count = 0;
public void DoProcessing(IProgress<int> progress, bool isParallel)
{
var filters = new String[] { "jpg", "jpeg", "png" };
var files = GetFilesFrom(txt_input.Text, filters, true);
string[] array = files;
if (isParallel)
{
Parallel.For(0, array.Length, i =>
{
var url = array[i];
int width = int.Parse(txtWidth.Text);
int height = int.Parse(txtHeight.Text);
object b = new object();
lock (b)
{
Image image = Image.FromFile(url);
string outputUrl = url.Replace(txt_input.Text, txt_output.Text);
using (Image thumb = image.GetThumbnailImage(width, height, () => false, IntPtr.Zero))
{
System.IO.FileInfo file = new System.IO.FileInfo(outputUrl);
file.Directory.Create();
thumb.Save(outputUrl);
image.Dispose();
}
if (progress != null)
{
Interlocked.Increment(ref count);
var percent = (count * 1.0 / array.Length) * 100;
Thread.Sleep(5);
lbl_file_processing.BeginInvoke(new Action(() => {
lbl_file_processing.Text = $"({count} / {array.Length})" + Path.GetFileName(url);
}));
progress.Report((int)percent);
}
}
});
}
else
{
for (int i = 0; i < array.Length; i++)
{
var url = array[i];
int width = int.Parse(txtWidth.Text);
int height = int.Parse(txtHeight.Text);
object b = new object();
lock (b)
{
Image image = Image.FromFile(url);
string outputUrl = url.Replace(txt_input.Text, txt_output.Text);
using (Image thumb = image.GetThumbnailImage(width, height, () => false, IntPtr.Zero))
{
System.IO.FileInfo file = new System.IO.FileInfo(outputUrl);
file.Directory.Create();
thumb.Save(outputUrl);
image.Dispose();
}
if (progress != null)
{
Interlocked.Increment(ref count);
var percent = (count * 1.0 / array.Length) * 100;
Thread.Sleep(5);
lbl_file_processing.BeginInvoke(new Action(() => {
lbl_file_processing.Text = $"({count} / {array.Length})" + Path.GetFileName( url);
}));
progress.Report((int)percent);
}
}
}
}
}
private async void btn_process_Click(object sender, EventArgs e)
{
count = 0;
var progress = new Progress<int>(percent =>
{
progressBar1.Value = percent;
lbl_percent.Text = percent + "%";
});
await Task.Run(() => DoProcessing(progress, chkParallel.Checked));
lbl_file_processing.Text = "Done!";
}
public String[] GetFilesFrom(String searchFolder, String[] filters, bool isRecursive)
{
List<String> filesFound = new List<String>();
var searchOption = isRecursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
foreach (var filter in filters)
{
filesFound.AddRange(Directory.GetFiles(searchFolder, String.Format("*.{0}", filter), searchOption));
}
return filesFound.ToArray();
}
}
}
Thanks for watching!