for (int i = 0; i < someList.length;i++){
Button button = new Button();
// Modify some button attributes height,width etc
var request = WebRequest.Create(current.thumbnail);
var response = request.GetResponse();
var stream = response.GetResponseStream();
button.BackgroundImage = Image.FromStream(stream);
stream.Close();
// and then i have these UI components that need updating (imagePanel is a FlowLayoutPanel)
imagePanel.Controls.Add(button);
imagePanel.Refresh();
progBar.PerformStep();
}
所以我目前遇到的问题是我用 webRequest/Response 阻塞了 UI 线程。
我猜我想做的是在 for 循环的每次迭代中创建和修改另一个按钮(包括背景图像) 线程。
当线程完成时有某种回调来更新 UI?
我可能还需要一些方法将在新线程上创建的按钮返回到主线程以更新 UI?
我是 c# 的初学者,过去没有真正接触过任何多线程,这是解决问题的方法吗, 还是我想的全错了。
最佳答案
我会使用 async/await和 WebClient 来处理这个
await Task.WhenAll(someList.Select(async i =>
{
var button = new Button();
// Modify some button attributes height,width etc
using (var wc = new WebClient())
using (var stream = new MemoryStream(await wc.DownloadDataTaskAsync(current.thumbnail)))
{
button.BackgroundImage = Image.FromStream(stream);
}
// and then i have these UI components that need updating (imagePanel is a FlowLayoutPanel)
imagePanel.Controls.Add(button);
imagePanel.Refresh();
progBar.PerformStep();
}));
关于线程完成后C#更新UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29793410/