【问题标题】:How can I change my code to use background workers instead of background threads如何更改我的代码以使用后台工作人员而不是后台线程
【发布时间】:2019-11-08 16:32:04
【问题描述】:

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

【问题讨论】:

  • 你查过Background Worker吗?互联网上有示例(例如在 BW 的文档中)。

标签: c# multithreading winforms backgroundworker


【解决方案1】:

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

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

【讨论】:

  • 顺便说一句,正如乔所说,我通过查找“BackgroundWorker”和“Invoke Lambda”来回答这个问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多