SoFunction
Updated on 2025-03-04

C# winfrom asynchronous loading of data does not affect the operation method of form UI

Preface

In an era of surging digital waves, program development is like a mysterious and magnificent magic castle, standing in the vast starry sky of technology. The characters in the code are like the twinkling stars, combined, intertwined and collided according to specific trajectories and rhythms, and are about to embark on a wonderful and creative journey full of infinite possibilities. When the blank document interface is like a deep universe waiting to be explored, programmers transform into fearless star pioneers, dancing lightly on the keyboard with their fingertips, preparing to use wisdom and logic to weave a program scroll that is enough to change the rules of the world's operation, and in the binary world of 0 and 1, they engrave the immortal mark of human innovation and breakthrough.

1. Background introduction

In WinForms applications, if data loading is a time-consuming operation (such as reading large amounts of data from the database, loading large files, etc.), loading directly in the main thread will cause the UI to freeze. This is because WinForms' UI is single-threaded, and when the main thread is blocked, it cannot handle other UI-related tasks, such as user input, interface updates, etc. Asynchronous loading of data can solve this problem, allowing data to be loaded in the background thread, and the UI thread can continue to respond to user operations.

2. Use BackgroundWorker component to implement asynchronous loading of data

2.1 Adding BackgroundWorker Component

Add BackgroundWorker Components: In WinForms Designer, locate BackgroundWorker from the Components tab of the toolbox and drag and drop it onto the form.

2.2 Handling DoWork events

Handling DoWork events: This event is executed in a background thread and is used to load data. For example, if you want to load data from a database, you can write database access code in this event handler.

   private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
   {
       // Here we simulate a time-consuming data loading operation, such as reading data from the database       (5000);
       // Suppose here is the code that actually gets data from the database       List<string> data = new List<string>();
       ("Data 1");
       ("Data 2");
       // Return the loaded data as the result        = data;
   }

Handle RunWorkerCompleted event: When the background operation is completed, this event will be triggered in the main thread. Here you can update the UI to display the loaded data.

   private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
   {
       if ( == null)
       {
           List<string> data = (List<string>);
           // Suppose dataGridView1 is a DataGridView control used to display data            = data;
       }
       else
       {
           // Handle error situations, such as displaying error messages           ("Data loading error:" + );
       }
   }

Start asynchronous operation: You can start BackgroundWorker at a button click event or a form load event.

   private void button1_Click(object sender, EventArgs e)
   {
       if (!)
       {
           ();
       }
   }

Use async/await to implement asynchronous loading of data (if the data loading operation itself supports asynchronous methods)
Suppose you have an asynchronous method to load data, such as an asynchronous method to get data from the network.

   private async void button2_Click(object sender, EventArgs e)
   {
       // Assume LoadDataAsync is an asynchronous method for loading data       List<string> data = await LoadDataAsync();
        = data;
   }

This LoadDataAsync method may use HttpClient to obtain data from the network, etc., and use async and await keywords to implement asynchronous operations. For example:

   private async Task<List<string>> LoadDataAsync()
   {
       using (HttpClient client = new HttpClient())
       {
           HttpResponseMessage response = await ("/api/data");
           if ()
           {
               string json = await ();
               // Suppose here is the code to deserialize JSON data into List<string>               return &lt;List&lt;string&gt;&gt;(json);
           }
           else
           {
               throw new Exception("Data loading failed");
           }
       }
   }

3. Extended content

3.1 Error handling and progress reporting

Error handling and progress reporting: In BackgroundWorker, errors can be handled through properties, and events can also be used to report progress. For async/await, you can use the try-catch block to handle exceptions, and if there is progress information on the loading process, you can update the UI to display progress through events or the returned progress object.

3.2 Thread Safety

Thread Safety: When updating the UI, make sure that the operations are thread-safe. For BackgroundWorker, because the RunWorkerCompleted event is triggered in the main thread, the UI can be updated directly. However, if it is in other asynchronous scenarios, you may need to use the Invoke or BeginInvoke method to ensure that the UI is updated in the main thread to avoid cross-thread access exceptions.

Conclusion

The above is the detailed content of how C# winfrom asynchronous loading data does not affect the operation of the form UI. For more information about asynchronous loading data in C# winfrom, please pay attention to my other related articles!