[英]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.我有一个 winform 应用程序发出 API 请求并将响应写入文本框。 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.请求可能需要几分钟才能完成,并防止应用程序在我使用后台线程的每个 API 请求上冻结。 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:要消除定义的委托,请将 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();
});
}
}
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取决于您是否要在其他地方重用 GetAPI 数据
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.