如何更改我的代码以使用后台工作者而不是后台线程

How can I change my code to use background workers instead of background threads

我有一个 winform 应用程序发出 API 请求并将响应写入文本框。这些请求可能需要几分钟才能完成,并防止应用程序在我使用后台线程的每个 API 请求上冻结。但是,我想改用后台工作人员来避免每个表单控件所需的大量委托。如何更改我的代码以改为使用后台工作程序?

我环顾四周,我发现的关于后台工作者的大部分信息都与进度条有关,我不知道如何使用后台工作者来完成我正在做的事情。

 private delegate void TextBox1WriteDelegate(string i);
    private void TextBox1Write(string i)
    {
        textBox1.Text = i;
    }

    public void GetApiData()
    {
        using (HttpClient httpClient = new HttpClient())
        {
            var response = httpClient.GetAsync("http://apiendpoint.com").Result;
            textBox1.Invoke(new TextBox1WriteDelegate(TextBox1Write), response.RequestMessage.ToString());
        }
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Thread t = new Thread(GetApiData);
        t.IsBackground = true;
        t.Start();
    }

做后台 worker 很容易.. 像这样:

    private void button2_Click(object sender, EventArgs e)
    {
        BackgroundWorker bw = new BackgroundWorker();

        bw.DoWork += (a, b) => GetApiData();
    }

但是,这不一定能解决委托问题...

要消除定义的委托,将 GetApiData() 更改为:

    public void GetApiData()
    {
        using (HttpClient httpClient = new HttpClient())
        {
            var response = httpClient.GetAsync("http://apiendpoint.com").Result;
            textBox1.Invoke((Action)delegate 
            { 
              textBox1.Text = response.RequestMessage.ToString(); 
            });
        }
    }

然后您可以删除委托定义。

你也可以一路走下去,这样做:

    private void button3_click(object sender, EventArgs e)
    {
        BackgroundWorker bw = new BackgroundWorker();

        bw.DoWork += (a, b) =>
        {
            using (HttpClient httpClient = new HttpClient())
            {
                var response = httpClient.GetAsync("http://apiendpoint.com").Result;
                textBox1.Invoke((Action)delegate 
                { 
                   textBox1.Text = response.RequestMessage.ToString(); 
                });
            }
        };
    }

取消所有功能。取决于您是否打算在其他地方重用 GetAPI 数据