c# - 如何更改我的代码以使用后台工作人员而不是后台线程
问题描述
我有一个 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();
}
解决方案
做后台工作者很容易..像这样:
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 数据
推荐阅读
- python-requests - PYTHON:使用请求将多个图像保存到文件夹中
- python-3.x - 如何在 Python 中正确格式化输出?
- spring - 从 Spring 控制器将响应作为键值对发送?
- elixir - 为什么我在记录时出现 Timber logger 500 HTTP 错误?
- scala - 如何使列表包含整数和字符串?仅使用列表的挑战
- c++ - 更好的多功能调用设计
- r - 选择较长的并给出 R 向量中较短的索引
- vbscript - 如何使用 VBSCRIPT 获取下载路径
- c - C程序在循环中创建指针导致内存泄漏
- python - 根据其他列中的值对列中数据框行的子集应用函数