首页 > 解决方案 > 如何更改我的代码以使用后台工作人员而不是后台线程

问题描述

我有一个 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();
    }

标签: c#multithreadingwinformsbackgroundworker

解决方案


做后台工作者很容易..像这样:

    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 数据


推荐阅读