Home >Backend Development >C++ >How to Safely Update a GUI from a Background Thread in C#?
C# GUI Thread Safety Update Guide
Updating the GUI from a background thread is a tricky problem. Attempting to do so directly may result in unusual or unexpected behavior.
1. Initial setup: Instantiate a BackgroundWorker and configure its event handlers.
<code class="language-csharp">private BackgroundWorker _backgroundWorker; _backgroundWorker = new BackgroundWorker(); _backgroundWorker.DoWork += backgroundWorker_DoWork; _backgroundWorker.ProgressChanged += backgroundWorker_ProgressChanged; _backgroundWorker.WorkerReportsProgress = true;</code>
2. Background tasks: In the DoWork event handler, execute long-running tasks and report progress periodically.
<code class="language-csharp">public void backgroundWorker_DoWork(object sender, DoWorkEventArgs e) { // ... 执行你的任务 object param = "一些数据"; _backgroundWorker.ReportProgress(0, param); }</code>
3. Progress report: In the ProgressChanged event handler, update the GUI with the reported progress.
<code class="language-csharp">private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e) { // 使用e.ProgressPercentage和e.UserState更新UI }</code>
4. Start background task: Call RunWorkerAsync to start the background task.
<code class="language-csharp">_backgroundWorker.RunWorkerAsync();</code>
5. Continuous scheduling (optional): If you need to repeat the task regularly, you can add the following code in the RunWorkerCompleted event handler.
<code class="language-csharp">void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { // UI 更新 Thread.Sleep(10000); Update(); }</code>
The above is the detailed content of How to Safely Update a GUI from a Background Thread in C#?. For more information, please follow other related articles on the PHP Chinese website!