Skip to main content

[CSHARP] Load BigData Async with Reactive .NET

Chào mọi người, bài viết hôm nay mình sẽ hướng dẫn các bạn sử dụng thư viện Reactive, để load dữ liệu lớn (Big data) bất đồng bộ vào Gridview C# Winform.

[C#] Sử dụng Reactive NET load Big data vào Gridview 

Reactive .net (Rx.net) là lập trình với các dữ liệu nguồn không đồng bộ.

Một Stream khi chạy bất đồng bộ sẽ sẽ ra một trong 3 cơ chế: OnCompleted, OnErrorOnNext.

Để tìm hiểu kỹ về Rx.NET các bạn truy cập vào link sau để xem hướng dẫn cụ thể:

Demo ví dụ dưới đây mình sẽ load dữ liệu Big Data khoảng 1.2 triệu dòng vào data Gridview.

Câu lệnh truy vấn này khi mình thực hiện truy vấn dưới Sqlserver là mất 13s để hoàn thành.

Và yêu cầu là làm sao mình có thể load dữ liệu lớn vậy vào Data Gridview, nếu chúng ta load đồng bộ thì Winform sẽ treo UI.

Dưới đây là mình sẽ sử dụng Rx.Net để load dữ liệu, và mỗi lần load mình chỉ load 5000 dòng (có thể cấu hình thay đổi), và hiển thị dữ liệu cho người dùng.

Giao diện demo ứng dụng Load BigData with RX.NET C#:


Đầu tiên các bạn cần cài đặt thư viện Rx.NET từ nuget
Install-Package System.Reactive -Version 4.3.2

FULL CODE.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Reactive.Linq;
using System.Reactive.Concurrency;
using System.Threading;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        string connectionString = $"Server=xxx;Database=xxx;User Id=xxx; Password =xxxx; Connection Timeout=3";
  

        public class HeThong
        {
            public string ngay { get; set; }
            public string thaotac { get; set; }
            public string ip { get; set; }
            public string tenmay { get; set; }
        }
        public IEnumerable<HeThong> GetHeThongs()
        {
            using (var connection = new SqlConnection(connectionString))
            {
                using (var cmd = connection.CreateCommand())
                {
                    cmd.CommandText =
                        "SELECT isnull(format(tgbd_scan, 'dd/MM/yyyy HH:mm:ss'), '') AS ngay , isnull(makien, '') as thaotac, isnull(nguoitd, '') as ip, isnull(makienvao,'') as tenmay FROM dbo.tbl_nhaplieu_wc order by stt DESC";                  
                    connection.Open();
                    var reader = cmd.ExecuteReader();
                    using (reader)
                    {
                        while (reader.Read())
                        {
                            var hethong = new HeThong
                            {
                                ngay = reader.GetString(0),
                                thaotac = reader.GetString(1),
                                ip = reader.GetString(2),
                                tenmay = reader.GetString(3)
                            };

                            yield return hethong;
                        }
                    }
                }
            }
        }

        IDisposable subcription;
        private void button1_Click(object sender, EventArgs e)
        {
            List<HeThong> companies = new List<HeThong>();
            var bindingList = new BindingList<HeThong>(companies);
            var source = new BindingSource(bindingList, null);
            source.ResetBindings(false);
            gridControl1.DataSource = source;
            bindingList.ResetBindings();
            label1.Text = string.Format("Loading data...");
            var obverse = GetHeThongs().ToObservable(ThreadPoolScheduler.Instance).Buffer(Convert.ToInt32(textBox1.Text)).ObserveOn(SynchronizationContext.Current);

            subcription = obverse.Subscribe(loadedData =>
                {
                    companies.AddRange(loadedData);
                    source.ResetBindings(false);
                    label1.Text = string.Format("Loaded {0} rows", companies.Count.ToString("#,000"));
                },
                exception => { label1.Text = exception.Message; },
                () => { label1.Text = "Finished loading data"; });
        }

        private void button2_Click(object sender, EventArgs e)
        {
            subcription.Dispose();
        }
    }
}

Chúc mọi người thành công với tiện ích trên.

DOWNLOAD SOURCE CODE

PASSWORD UNZIP: HUNG.PRO.VN
Comment Policy: Silahkan tuliskan komentar Anda yang sesuai dengan topik postingan halaman ini. Komentar yang berisi tautan tidak akan ditampilkan sebelum disetujui.
Buka Komentar
Tutup Komentar