Home  >  Article  >  Backend Development  >  Detailed introduction to the sample code of Winform in c# to implement multi-threaded asynchronous update of UI

Detailed introduction to the sample code of Winform in c# to implement multi-threaded asynchronous update of UI

黄舟
黄舟Original
2017-03-21 11:18:421872browse

This article mainly introduces the multi-threaded asynchronous update UI (progress and status information) implemented by Winform in c#. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor and take a look.

Introduction

When developing Winform programs that require a large amount of data reading and writing operations, it often takes a certain amount of time. , however, during this time period, the interface UI cannot be updated, causing the interface to be in a state of suspended animation in the eyes of the user, resulting in a bad user experience. Therefore, in applications that operate a large amount of data, multi-threading needs to be used to handle this situation. It is very convenient to use multi-threading in C#. You only need to use the Start method of an instance of System.Threading.Thread, but how to realize the interaction between multi-threads is not that simple. This article implements the use of sub-threads to process data and updates the UI status of the main thread in real time. Let’s start step by step to implement the demo program of asynchronous thread update UI.

Application background

Write a certain amount of data to a text file, and at the same time, the real-time progress of writing the data needs to be reflected in the main interface. Requirement: The written data needs to be encapsulated into a class.

Implementation process

1. First create a winform project, drag a button, a progressbar, and a label on the main form. As shown below.

#2. Write a class (WriteDate) for processing data. The source code is as follows.

 public class DataWrite
 {
  public delegate void UpdateUI(int step);//声明一个更新主线程的委托
  public UpdateUI UpdateUIDelegate;

  public delegate void AccomplishTask();//声明一个在完成任务时通知主线程的委托
  public AccomplishTask TaskCallBack;
  
  public void Write(object lineCount)
  {
   StreamWriter writeIO = new StreamWriter("text.txt", false, Encoding.GetEncoding("gb2312"));
   string head = "编号,省,市";
   writeIO.Write(head);
   for (int i = 0; i < (int)lineCount; i++)
   {
    writeIO.WriteLine(i.ToString() + ",湖南,衡阳");
    //写入一条数据,调用更新主线程ui状态的委托
    UpdateUIDelegate(1);
   }
   //任务完成时通知主线程作出相应的处理
   TaskCallBack();
   writeIO.Close();
  }
 }

3. The code in the main interface is as follows:

First, a delegate must be established to implement thread update controls for non-created controls.

delegate void AsynUpdateUI(int step);

Then write multiple threads to start the method of writing data and the callback function.

  private void btnWrite_Click(object sender, EventArgs e)
  {
   int taskCount = 10000; //任务量为10000
   this.pgbWrite.Maximum = taskCount;
   this.pgbWrite.Value = 0;

   DataWrite dataWrite = new DataWrite();//实例化一个写入数据的类
   dataWrite.UpdateUIDelegate += UpdataUIStatus;//绑定更新任务状态的委托
   dataWrite.TaskCallBack += Accomplish;//绑定完成任务要调用的委托

   Thread thread = new Thread(new ParameterizedThreadStart(dataWrite.Write));
   thread.IsBackground = true;
   thread.Start(taskCount);
  }

  //更新UI
  private void UpdataUIStatus(int step)
  {
   if (InvokeRequired)
   {
    this.Invoke(new AsynUpdateUI(delegate(int s)
    {
     this.pgbWrite.Value += s;
     this.lblWriteStatus.Text = this.pgbWrite.Value.ToString() + "/" + this.pgbWrite.Maximum.ToString();
    }), step);
   }
   else
   {
    this.pgbWrite.Value += step;
    this.lblWriteStatus.Text = this.pgbWrite.Value.ToString() + "/" + this.pgbWrite.Maximum.ToString();
   }
  }

  //完成任务时需要调用
  private void Accomplish()
  {
   //还可以进行其他的一些完任务完成之后的逻辑处理
   MessageBox.Show("任务完成");
  }

The effect is as follows:

Summary

There are many ways to implement asynchronous update ui method, but I think this method is more flexible and can obtain the status of the task in real time and process it accordingly. This mode is also suitable for using multiple threads to write different data to different files at the same time.

The above is the detailed content of Detailed introduction to the sample code of Winform in c# to implement multi-threaded asynchronous update of UI. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn