简体   繁体   中英

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

I have a winform application making API requests and writing the responses to text boxes. The requests can take a few minutes to complete and to prevent the application freezing up on each API request I'm using background threads. However I would like to use background workers instead to avoid the large number of delegates needed for each form control. How can I change my code to use background workers instead?

I've looked around and most of the information I found on background workers are related to progress bars and I can't work out how to use background workers for what I'm doing.

 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();
    }

It's easy enough to do the Background worker.. as such:

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

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

But, that doesn't necessarily fix the delegate issue...

To eliminate the defined delegate, change GetApiData() to be:

    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(); 
            });
        }
    }

You can then eliminate the delegate definition.

You could go also go all the way and do this:

    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(); 
                });
            }
        };
    }

Eliminating all of the functions. Depends on whether you are going to reuse GetAPI data somewhere else

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM