How to implement asynchronous updating of control data in WinForms?

In WinForms, updating control data asynchronously can be achieved by using either the Control.BeginInvoke method or Task.Run.

  1. Initiate a control’s invoke.
private async void UpdateControlDataAsync()
{
    await Task.Run(() =>
    {
        // 在异步线程中更新控件数据
        string newData = FetchDataFromServer();
        
        // 切换回UI线程更新控件数据
        this.BeginInvoke((Action)(() =>
        {
            // 更新控件数据
            label1.Text = newData;
        }));
    });
}
  1. Execute a task.
private async void UpdateControlDataAsync()
{
    string newData = await Task.Run(() =>
    {
        // 在异步线程中更新控件数据
        return FetchDataFromServer();
    });

    // 更新控件数据
    label1.Text = newData;
}

The FetchDataFromServer method is used to retrieve data in an asynchronous thread. By placing the code that updates the UI within this.BeginInvoke or await Task.Run, it ensures that the data update operation is performed on the UI thread, avoiding thread conflicts and UI freezes.

bannerAds