【问题标题】:Winforms C#: async initializeWinforms C#:异步初始化
【发布时间】:2021-03-18 12:27:22
【问题描述】:

我有一个Winform C# 应用程序,它有一个DataGridView。我打算将来自Azure table storage 的数据加载到其中,同时表单为initializing。恐怕如果我从Azure table storage 加载这么多数据,我的应用程序就会崩溃。我可以在表单构造函数中使用AsyncAzure table storage 加载数据吗?

【问题讨论】:

    标签: winforms


    【解决方案1】:

    您通常会在Form_Load 事件中进行此类工作。例如:

    using System;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    
    namespace WindowsFormsApp1
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private async void Form1_Load(object sender, EventArgs e)
            {
                await RefreshDataAsync();
            }
    
            private async void button1_Click(object sender, EventArgs e)
            {
                await RefreshDataAsync();
            }
    
            private async Task RefreshDataAsync()
            {
                button1.Enabled = false;
                listBox1.Items.Clear();
    
                try
                {
                    var data = await GetDataFromDataSourceAsync();
                    foreach(var item in data)
                    {
                        listBox1.Items.Add(item);
                    }
                }
                finally
                {
                    button1.Enabled = true;
                }
            }
        }
    }
    

    因此,您将创建一个“刷新数据”方法,并让您的 Form_Load 事件调用它。由于您隔离了刷新代码,因此您也可以让其他东西调用它,例如按钮。

    WinForm 事件,例如Form_Load 或按钮单击事件,只需向它们添加async 关键字即可实现异步。更多关于here的信息。

    【讨论】:

    • 非常感谢您的支持,它帮助我解决了我的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-28
    • 2022-06-13
    • 2018-06-26
    • 1970-01-01
    • 2011-10-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多